@dsh-agentic-roleplay/core 0.3.1 → 0.3.3

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 (39) hide show
  1. package/lib/authoring.js +13 -2
  2. package/lib/child-lPncV1ps.js +380 -0
  3. package/lib/client.js +1526 -356
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +1 -1
  6. package/lib/deliver-De62a8i9.js +1929 -0
  7. package/lib/doctor-chat-ByDfCMeo.js +17 -0
  8. package/lib/doctor.js +95 -0
  9. package/lib/{documents-DtlY2IRt.js → documents-Do4lz4SB.js} +549 -64
  10. package/lib/{gallery-DACG5eh2.js → gallery-CtFDL22W.js} +2 -2
  11. package/lib/{generator-DGYcLMp7.js → generator-B6FxlKOV.js} +2 -378
  12. package/lib/hooks-Ka22sFNy.js +1019 -0
  13. package/lib/images.js +3 -3
  14. package/lib/index.js +303 -190
  15. package/lib/language-DWVwi1R7.js +520 -0
  16. package/lib/narration-DK2kiIjE.js +141 -0
  17. package/lib/orchestration.js +777 -2542
  18. package/lib/{packs-CkRZDCsV.js → packs-BYjrAen6.js} +4 -518
  19. package/lib/{presenter-agent-PK9JYExk.js → presenter-agent-Dt21K96b.js} +4 -3
  20. package/lib/{deliver-BDW5WZvc.js → reflection-md7BCYCl.js} +350 -769
  21. package/lib/{narration-5ig7Dg28.js → settings-CA6icLL_.js} +156 -141
  22. package/package.json +3 -2
  23. package/prompts/en/doctor/persona.md +1 -0
  24. package/prompts/en/doctor/procedure.md +5 -0
  25. package/prompts/en/doctor/welcome.md +1 -0
  26. package/prompts/en/import/character.md +1 -0
  27. package/prompts/en/roleplay/dice.md +7 -0
  28. package/prompts/en/roleplay/game-master.md +2 -0
  29. package/prompts/en/roleplay/reflection-check.md +5 -0
  30. package/prompts/en/roleplay/reflection.md +5 -1
  31. package/prompts/zh/doctor/persona.md +1 -0
  32. package/prompts/zh/doctor/procedure.md +5 -0
  33. package/prompts/zh/doctor/welcome.md +1 -0
  34. package/prompts/zh/import/character.md +1 -0
  35. package/prompts/zh/roleplay/dice.md +7 -0
  36. package/prompts/zh/roleplay/game-master.md +2 -0
  37. package/prompts/zh/roleplay/reflection-check.md +5 -0
  38. package/prompts/zh/roleplay/reflection.md +5 -1
  39. package/lib/src-CWTNeL6Y.js +0 -128
@@ -1,13 +1,16 @@
1
- import { A as formatIssue, C as PLOTS_FILE_NAME, D as readDocument, E as plotReferenceProblems, F as languageOf, I as listFiles, J as INTENT_HORIZONS, L as promptProblem, O as errorMessage, R as shippedLanguages, T as parsePlotsFile, U as InvalidWorldError, X as INTENT_TYPES, Y as INTENT_STATUSES, _ as API_PREFIX, b as isStoryLanguage, j as PROMPTS_FOLDER, k as Reader, v as LANGUAGE_NAMES, w as loadPlots, x as textLanguage, y as STORY_LANGUAGES, z as shippedPromptsDirectory } from "./packs-CkRZDCsV.js";
2
- import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
3
- import { A as runChild, C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-DGYcLMp7.js";
1
+ import { _ as API_PREFIX, b as INTENT_TYPES, v as INTENT_HORIZONS, y as INTENT_STATUSES } from "./packs-BYjrAen6.js";
2
+ import { c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, s as VARIABLE_KINDS } from "./settings-CA6icLL_.js";
3
+ import { E as InvalidWorldError, S as shippedPromptsDirectory, b as promptProblem, c as parsePlotsFile, d as errorMessage, f as Reader, i as textLanguage, l as plotReferenceProblems, m as PROMPTS_FOLDER, n as STORY_LANGUAGES, o as PLOTS_FILE_NAME, p as formatIssue, r as isStoryLanguage, s as loadPlots, t as LANGUAGE_NAMES, u as readDocument, v as languageOf, x as shippedLanguages, y as listFiles } from "./language-DWVwi1R7.js";
4
+ import { a as runChild } from "./child-lPncV1ps.js";
5
+ import { C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-B6FxlKOV.js";
4
6
  import { basename, dirname, join, relative, sep } from "node:path";
5
7
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
6
8
  import { createHash, randomUUID } from "node:crypto";
7
9
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
10
+ import { inflateSync } from "node:zlib";
8
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
12
  import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
10
- import { MAX_ROUTINE_WINDOWS, MINUTE, MONTH_NAMES, SEASONS, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue, writeCalendar } from "@dsh-agentic-roleplay/state";
13
+ import { MAX_ROUTINE_WINDOWS, MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue, writeCalendar } from "@dsh-agentic-roleplay/state";
11
14
  import { lookup } from "node:dns";
12
15
  import { request } from "node:http";
13
16
  import { request as request$1 } from "node:https";
@@ -113,6 +116,25 @@ const WEEKDAY_NAMES = [
113
116
  "sat"
114
117
  ];
115
118
  //#endregion
119
+ //#region ../dsh-roleplay-model/src/dice.ts
120
+ /** What a band of a check makes of an attempt; the same three results a round's outcome has. */
121
+ const DICE_RESULTS = [
122
+ "succeeded",
123
+ "partial",
124
+ "failed"
125
+ ];
126
+ /** How a roll is read: by its total, or by how many of the dice came up high enough. */
127
+ const DICE_READINGS = ["total", "successes"];
128
+ /**
129
+ * What the value is compared with: `absolute` reads the value itself, `over` the amount by which it beats the target
130
+ * (a difficulty to meet or exceed), `under` the amount by which it stays below the target (a skill to roll under).
131
+ */
132
+ const DICE_COMPARISONS = [
133
+ "absolute",
134
+ "over",
135
+ "under"
136
+ ];
137
+ //#endregion
116
138
  //#region ../dsh-roleplay-model/src/lore.ts
117
139
  const LORE_KINDS = [
118
140
  "history",
@@ -133,6 +155,179 @@ const LORE_SUBJECT_KINDS = [
133
155
  "lore"
134
156
  ];
135
157
  //#endregion
158
+ //#region src/host/import/card.ts
159
+ /** The file is not a character card this importer reads. The message says why, for the person who uploaded it. */
160
+ var ImportCardError = class extends Error {};
161
+ const PNG_SIGNATURE = Buffer.from([
162
+ 137,
163
+ 80,
164
+ 78,
165
+ 71,
166
+ 13,
167
+ 10,
168
+ 26,
169
+ 10
170
+ ]);
171
+ const TEXT_CHUNKS = /* @__PURE__ */ new Set([
172
+ "tEXt",
173
+ "iTXt",
174
+ "zTXt"
175
+ ]);
176
+ /** The keywords a card's data is stored under, the newer one first. */
177
+ const CARD_KEYWORDS = ["ccv3", "chara"];
178
+ function chunksOf(file) {
179
+ const chunks = [];
180
+ let at = PNG_SIGNATURE.length;
181
+ while (at + 12 <= file.length) {
182
+ const length = file.readUInt32BE(at);
183
+ const end = at + 12 + length;
184
+ if (end > file.length) throw new ImportCardError("the PNG file is damaged: a part of it is cut off");
185
+ chunks.push({
186
+ type: file.toString("latin1", at + 4, at + 8),
187
+ data: file.subarray(at + 8, at + 8 + length),
188
+ raw: file.subarray(at, end)
189
+ });
190
+ at = end;
191
+ }
192
+ return chunks;
193
+ }
194
+ /** The keyword and text of a PNG text chunk. */
195
+ function textOf(chunk) {
196
+ const end = chunk.data.indexOf(0);
197
+ if (end < 0) return void 0;
198
+ const keyword = chunk.data.toString("latin1", 0, end);
199
+ const rest = chunk.data.subarray(end + 1);
200
+ if (chunk.type === "tEXt") return {
201
+ keyword,
202
+ text: rest.toString("latin1")
203
+ };
204
+ if (chunk.type === "zTXt") return {
205
+ keyword,
206
+ text: inflateSync(rest.subarray(1)).toString("latin1")
207
+ };
208
+ const compressed = rest[0] === 1;
209
+ let from = 2;
210
+ for (let skipped = 0; skipped < 2; skipped += 1) from = rest.indexOf(0, from) + 1;
211
+ if (from <= 0) return void 0;
212
+ const body = rest.subarray(from);
213
+ return {
214
+ keyword,
215
+ text: (compressed ? inflateSync(body) : body).toString("utf8")
216
+ };
217
+ }
218
+ /** The PNG without its text chunks: the picture, with none of the card's data in it. */
219
+ function pictureOf(file) {
220
+ return Buffer.concat([PNG_SIGNATURE, ...chunksOf(file).filter((chunk) => !TEXT_CHUNKS.has(chunk.type)).map((chunk) => chunk.raw)]);
221
+ }
222
+ function jsonOf(file, name) {
223
+ if (file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
224
+ const found = /* @__PURE__ */ new Map();
225
+ for (const chunk of chunksOf(file)) {
226
+ if (!TEXT_CHUNKS.has(chunk.type)) continue;
227
+ const text = textOf(chunk);
228
+ if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
229
+ }
230
+ const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
231
+ if (keyword === void 0) throw new ImportCardError(`${name} is a PNG picture with no character card in it`);
232
+ try {
233
+ return JSON.parse(Buffer.from(found.get(keyword).trim(), "base64").toString("utf8"));
234
+ } catch {
235
+ throw new ImportCardError(`the card data in ${name} is not readable`);
236
+ }
237
+ }
238
+ try {
239
+ return JSON.parse(file.toString("utf8").replace(/^/, ""));
240
+ } catch {
241
+ throw new ImportCardError(`${name} is neither a PNG picture with a card in it nor a JSON card`);
242
+ }
243
+ }
244
+ const URL_PATTERN = /https?:\/\/[^\s"'`<>()[\]{}\\|^]+/gi;
245
+ /** Every web address in the strings of a document, at any depth; template placeholders and trailing punctuation are not part of one. */
246
+ function urlsOf(value) {
247
+ const found = /* @__PURE__ */ new Set();
248
+ const visit = (node, depth) => {
249
+ if (depth > 32) return;
250
+ if (typeof node === "string") for (const match of node.matchAll(URL_PATTERN)) {
251
+ const url = match[0].replace(/[.,;:!?*_~]+$/, "");
252
+ if (!url.includes("$") && url.length <= 2e3) found.add(url);
253
+ }
254
+ else if (Array.isArray(node)) for (const entry of node) visit(entry, depth + 1);
255
+ else if (typeof node === "object" && node !== null) for (const entry of Object.values(node)) visit(entry, depth + 1);
256
+ };
257
+ visit(value, 0);
258
+ return [...found];
259
+ }
260
+ const object$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
261
+ const text$2 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
262
+ const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
263
+ function entryOf(value, index) {
264
+ const entry = object$1(value);
265
+ if (entry === void 0) return void 0;
266
+ const position = entry["position"];
267
+ return {
268
+ id: `entry:${index}`,
269
+ title: text$2(entry["comment"]).trim() || text$2(entry["name"]).trim(),
270
+ keys: texts(entry["keys"]),
271
+ secondaryKeys: texts(entry["secondary_keys"]),
272
+ content: text$2(entry["content"]),
273
+ enabled: entry["enabled"] !== false,
274
+ constant: entry["constant"] === true,
275
+ selective: entry["selective"] === true,
276
+ position: typeof position === "string" ? position : typeof position === "number" ? String(position) : ""
277
+ };
278
+ }
279
+ /**
280
+ * Reads a character card: a PNG with the card in its text chunk (the newer `ccv3` chunk when there is one), or the JSON of a card.
281
+ * Only V2 and V3 cards are read; a V2 card is carried over into the V3 shape, whose fields are a superset.
282
+ * @throws {ImportCardError} when the file is not such a card.
283
+ */
284
+ function readCard(file, name) {
285
+ const root = object$1(jsonOf(file, name));
286
+ const spec = root === void 0 ? void 0 : root["spec"];
287
+ if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text$2(spec)}" card: only V2 and V3 cards are read`);
288
+ const data = object$1(root?.["data"]);
289
+ if (data === void 0) throw new ImportCardError(`${name} has no card data`);
290
+ const cardName = text$2(data["name"]).trim();
291
+ if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
292
+ const book = object$1(data["character_book"]);
293
+ const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
294
+ const extensions = object$1(data["extensions"]) ?? {};
295
+ const scripts = [extensions["regex_scripts"], object$1(extensions["tavern_helper"])?.["scripts"]].reduce((count, list) => count + (Array.isArray(list) ? list.length : 0), 0);
296
+ return {
297
+ sourceSpec: spec,
298
+ name: cardName,
299
+ description: text$2(data["description"]),
300
+ personality: text$2(data["personality"]),
301
+ scenario: text$2(data["scenario"]),
302
+ firstMessage: text$2(data["first_mes"]),
303
+ alternateGreetings: texts(data["alternate_greetings"]),
304
+ messageExample: text$2(data["mes_example"]),
305
+ creatorNotes: text$2(data["creator_notes"]),
306
+ systemPrompt: text$2(data["system_prompt"]),
307
+ postHistoryInstructions: text$2(data["post_history_instructions"]),
308
+ tags: texts(data["tags"]),
309
+ creator: text$2(data["creator"]),
310
+ characterVersion: text$2(data["character_version"]),
311
+ ...book === void 0 ? {} : { book: {
312
+ name: text$2(book["name"]),
313
+ description: text$2(book["description"]),
314
+ entries
315
+ } },
316
+ ignored: {
317
+ scripts,
318
+ extensions: Object.keys(extensions).filter((key) => ![
319
+ "talkativeness",
320
+ "fav",
321
+ "world",
322
+ "depth_prompt"
323
+ ].includes(key))
324
+ },
325
+ urls: urlsOf(data)
326
+ };
327
+ }
328
+ /** Whether a file looks like a PNG, so that its picture can be kept. */
329
+ const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
330
+ //#endregion
136
331
  //#region src/shared/import-card.ts
137
332
  /** The message the plugin sends on the player's behalf to start the import in the new world's authoring chat. */
138
333
  const IMPORT_COMMAND = "/import-st";
@@ -719,7 +914,7 @@ function parseWorldInfoEdit(value) {
719
914
  const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
720
915
  if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
721
916
  const edit = {};
722
- for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings") problems.push(`there is no field "${key}"`);
917
+ for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "tools") problems.push(`there is no field "${key}"`);
723
918
  for (const key of TEXT_FIELDS) {
724
919
  if (input[key] === void 0) continue;
725
920
  if (typeof input[key] === "string") edit[key] = input[key].trim();
@@ -733,17 +928,23 @@ function parseWorldInfoEdit(value) {
733
928
  if (input["alternateOpenings"] !== void 0) {
734
929
  const list = input["alternateOpenings"];
735
930
  const entries = Array.isArray(list) ? list.map((entry) => typeof entry === "object" && entry !== null ? entry : void 0) : void 0;
736
- if (entries === void 0 || entries.some((entry) => entry === void 0 || typeof entry["text"] !== "string" || entry["title"] !== void 0 && typeof entry["title"] !== "string")) problems.push("alternateOpenings must be a list of { title, text }");
931
+ if (entries === void 0 || entries.some((entry) => entry === void 0 || typeof entry["text"] !== "string" || entry["title"] !== void 0 && typeof entry["title"] !== "string" || entry["character"] !== void 0 && typeof entry["character"] !== "string")) problems.push("alternateOpenings must be a list of { title, text, character? }");
737
932
  else {
738
933
  const kept = entries.map((entry) => ({
739
934
  title: String(entry["title"] ?? "").trim(),
740
- text: String(entry["text"]).trim()
935
+ text: String(entry["text"]).trim(),
936
+ ...String(entry["character"] ?? "").trim() === "" ? {} : { character: String(entry["character"]).trim() }
741
937
  })).filter((entry) => entry.text !== "");
742
938
  if (kept.length > 30) problems.push(`there are more than 30 alternate openings`);
743
939
  if (kept.some((entry) => entry.text.length > 2e4)) problems.push(`an alternate opening is longer than ${MAX_OPENING_CHARS} characters`);
744
940
  edit["alternateOpenings"] = kept;
745
941
  }
746
942
  }
943
+ if (input["tools"] !== void 0) {
944
+ const board = parseSwitchboard(input["tools"], "tools");
945
+ if (typeof board === "string") problems.push(board);
946
+ else edit["tools"] = board;
947
+ }
747
948
  if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
748
949
  if (edit["name"] === "") problems.push("the world needs a name");
749
950
  if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
@@ -753,7 +954,7 @@ function parseWorldInfoEdit(value) {
753
954
  //#endregion
754
955
  //#region src/host/worlds/world-file.ts
755
956
  const WORLD_FILE_NAME = "world.json";
756
- /** `alternate_openings` is a list of `{ title, text }`: other first messages the player may start with. */
957
+ /** `alternate_openings` is a list of `{ title, text, character? }`: other first messages the player may start with, each for any character or for one playable character. */
757
958
  function readAlternateOpenings(reader) {
758
959
  const value = reader.raw("alternate_openings");
759
960
  if (value === void 0 || value === null) return void 0;
@@ -767,13 +968,26 @@ function readAlternateOpenings(reader) {
767
968
  const text = entry.string("text", { required: true })?.trim();
768
969
  if (text === void 0 || text === "") continue;
769
970
  if (text.length > 2e4) entry.fail("text", `is longer than ${MAX_OPENING_CHARS} characters`);
971
+ const character = entry.string("character")?.trim();
770
972
  openings.push({
771
973
  title: entry.string("title")?.trim() || text.slice(0, 40),
772
- text
974
+ text,
975
+ ...character === void 0 || character === "" ? {} : { character }
773
976
  });
774
977
  }
775
978
  return openings.length === 0 ? void 0 : openings;
776
979
  }
980
+ /** `tools`: switches by kind of agent and tool name; a world carried from a version with other tools still loads. */
981
+ function readTools(reader) {
982
+ const value = reader.raw("tools");
983
+ if (value === void 0) return void 0;
984
+ const board = parseSwitchboard(value, "tools");
985
+ if (typeof board === "string") {
986
+ reader.fail("tools", board.replace(/^"tools"\s*/, ""));
987
+ return;
988
+ }
989
+ return Object.keys(board).length === 0 ? void 0 : board;
990
+ }
777
991
  /** `rules` is one rule as text, or a list of them; blank ones are left out. */
778
992
  function readRules(reader) {
779
993
  const value = reader.raw("rules");
@@ -867,6 +1081,7 @@ function parseWorldFile(text) {
867
1081
  const clock = readClock(reader);
868
1082
  const variables = readVariableValues(reader);
869
1083
  const rules = readRules(reader);
1084
+ const tools = readTools(reader);
870
1085
  const alternateOpenings = readAlternateOpenings(reader);
871
1086
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
872
1087
  if (name === void 0 || issues.length > 0) return {
@@ -887,6 +1102,7 @@ function parseWorldFile(text) {
887
1102
  ...clock === void 0 ? {} : { clock },
888
1103
  ...variables === void 0 ? {} : { variables },
889
1104
  ...rules === void 0 ? {} : { rules },
1105
+ ...tools === void 0 ? {} : { tools },
890
1106
  ...alternateOpenings === void 0 ? {} : { alternateOpenings },
891
1107
  ...narrationVoice === void 0 ? {} : { narrationVoice }
892
1108
  }
@@ -2363,7 +2579,7 @@ const SOURCE_BUDGET_CHARS = 14e3;
2363
2579
  const MAX_TAGGED = 8;
2364
2580
  const MAX_MENTIONS = 6;
2365
2581
  const MIN_MENTION_CHARS = 2;
2366
- const text = (value) => typeof value === "string" ? value.trim() : "";
2582
+ const text$1 = (value) => typeof value === "string" ? value.trim() : "";
2367
2583
  const list = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() !== "" ? [entry.trim()] : []) : [];
2368
2584
  const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry)) : [];
2369
2585
  const put = (document, key, value) => {
@@ -2478,6 +2694,14 @@ const CHARACTER_SCHEMA = {
2478
2694
  required: ["with", "label"],
2479
2695
  additionalProperties: false
2480
2696
  }
2697
+ },
2698
+ knows: {
2699
+ type: "object",
2700
+ properties: {
2701
+ places: strs("Names from the list of places that they know of."),
2702
+ things: strs("Names from the list of things that they know of.")
2703
+ },
2704
+ additionalProperties: false
2481
2705
  }
2482
2706
  },
2483
2707
  required: [
@@ -2503,7 +2727,7 @@ function characterDocument(entity, answer, roster) {
2503
2727
  "age",
2504
2728
  "gender",
2505
2729
  "pronouns"
2506
- ]) put(document, field, text(answer[field]));
2730
+ ]) put(document, field, text$1(answer[field]));
2507
2731
  const playable = entity.player;
2508
2732
  const group = answer["kind"] === "group" && !playable;
2509
2733
  document["role"] = playable ? "playable" : "npc";
@@ -2514,10 +2738,10 @@ function characterDocument(entity, answer, roster) {
2514
2738
  "personality",
2515
2739
  "background",
2516
2740
  "appearance"
2517
- ]) document[field] = text(answer[field]);
2741
+ ]) document[field] = text$1(answer[field]);
2518
2742
  const speech = typeof answer["speech"] === "object" && answer["speech"] !== null ? answer["speech"] : {};
2519
2743
  document["speech"] = {
2520
- style: text(speech["style"]),
2744
+ style: text$1(speech["style"]),
2521
2745
  examples: list(speech["examples"]).slice(0, 8)
2522
2746
  };
2523
2747
  const start = {};
@@ -2526,17 +2750,17 @@ function characterDocument(entity, answer, roster) {
2526
2750
  ["public_state", "public_state"],
2527
2751
  ["inner_state", "inner_state"],
2528
2752
  ["activity", "activity"]
2529
- ]) put(start, to, text(given[from]));
2530
- const place = text(given["location"]) === "" ? void 0 : findEntity(roster, text(given["location"]), "place");
2531
- if (text(given["location"]) !== "" && place === void 0) notes.push(`${entity.name}: the place "${text(given["location"])}" is not one of the world's places, so the character starts nowhere`);
2753
+ ]) put(start, to, text$1(given[from]));
2754
+ const place = text$1(given["location"]) === "" ? void 0 : findEntity(roster, text$1(given["location"]), "place");
2755
+ if (text$1(given["location"]) !== "" && place === void 0) notes.push(`${entity.name}: the place "${text$1(given["location"])}" is not one of the world's places, so the character starts nowhere`);
2532
2756
  if (place !== void 0) {
2533
2757
  start["location"] = place.key;
2534
- put(start, "position", text(given["position"]));
2758
+ put(start, "position", text$1(given["position"]));
2535
2759
  }
2536
- const goals = objects(answer["goals"]).filter((goal) => text(goal["name"]) !== "").map((goal) => ({
2760
+ const goals = objects(answer["goals"]).filter((goal) => text$1(goal["name"]) !== "").map((goal) => ({
2537
2761
  type: "agenda",
2538
- name: text(goal["name"]),
2539
- ...text(goal["description"]) === "" ? {} : { description: text(goal["description"]) },
2762
+ name: text$1(goal["name"]),
2763
+ ...text$1(goal["description"]) === "" ? {} : { description: text$1(goal["description"]) },
2540
2764
  status: "active"
2541
2765
  }));
2542
2766
  put(start, "intents", goals);
@@ -2544,20 +2768,30 @@ function characterDocument(entity, answer, roster) {
2544
2768
  const seen = /* @__PURE__ */ new Set([entity.key]);
2545
2769
  const relationships = [];
2546
2770
  for (const relation of objects(answer["relationships"])) {
2547
- const other = findEntity(roster, text(relation["with"]), "character");
2771
+ const other = findEntity(roster, text$1(relation["with"]), "character");
2548
2772
  if (other === void 0) {
2549
- notes.push(`${entity.name}: the relationship with "${text(relation["with"])}" names nobody in the world`);
2773
+ notes.push(`${entity.name}: the relationship with "${text$1(relation["with"])}" names nobody in the world`);
2550
2774
  continue;
2551
2775
  }
2552
- if (seen.has(other.key) || text(relation["label"]) === "") continue;
2776
+ if (seen.has(other.key) || text$1(relation["label"]) === "") continue;
2553
2777
  seen.add(other.key);
2554
2778
  relationships.push({
2555
2779
  to: other.key,
2556
- label: text(relation["label"]),
2557
- ...text(relation["summary"]) === "" ? {} : { summary: text(relation["summary"]) }
2780
+ label: text$1(relation["label"]),
2781
+ ...text$1(relation["summary"]) === "" ? {} : { summary: text$1(relation["summary"]) }
2558
2782
  });
2559
2783
  }
2560
2784
  put(document, "relationships", relationships.slice(0, 60));
2785
+ const knows = typeof answer["knows"] === "object" && answer["knows"] !== null ? answer["knows"] : {};
2786
+ const known = (names, kind) => [...new Set(names.flatMap((name) => {
2787
+ const found = findEntity(roster, name, kind);
2788
+ if (found === void 0) notes.push(`${entity.name}: "${name}" is not one of the world's ${kind === "place" ? "places" : "things"}, so they do not know of it`);
2789
+ return found === void 0 ? [] : [found.key];
2790
+ }))];
2791
+ const knowledge = {};
2792
+ put(knowledge, "locations", known(list(knows["places"]), "place"));
2793
+ put(knowledge, "items", known(list(knows["things"]), "thing"));
2794
+ put(document, "knowledge", Object.keys(knowledge).length === 0 ? void 0 : knowledge);
2561
2795
  return {
2562
2796
  document,
2563
2797
  notes
@@ -2602,30 +2836,30 @@ function placeDocument(entity, answer, roster) {
2602
2836
  id: entity.key,
2603
2837
  name: entity.name
2604
2838
  };
2605
- put(document, "description", text(answer["description"]));
2606
- const named = text(answer["parent"]) === "" ? entity.parent : text(answer["parent"]);
2839
+ put(document, "description", text$1(answer["description"]));
2840
+ const named = text$1(answer["parent"]) === "" ? entity.parent : text$1(answer["parent"]);
2607
2841
  const parent = named === void 0 ? void 0 : findEntity(roster, named, "place");
2608
2842
  if (named !== void 0 && (parent === void 0 || parent.key === entity.key)) notes.push(`${entity.name}: the place it is in, "${named}", is not one of the world's places`);
2609
2843
  if (parent !== void 0 && parent.key !== entity.key) document["parent"] = parent.key;
2610
- const features = objects(answer["features"]).filter((feature) => text(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
2844
+ const features = objects(answer["features"]).filter((feature) => text$1(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
2611
2845
  id: `feature-${index + 1}`,
2612
- name: text(feature["name"]),
2613
- ...text(feature["description"]) === "" ? {} : { description: text(feature["description"]) }
2846
+ name: text$1(feature["name"]),
2847
+ ...text$1(feature["description"]) === "" ? {} : { description: text$1(feature["description"]) }
2614
2848
  }));
2615
2849
  put(document, "features", features);
2616
2850
  const exits = [];
2617
2851
  const to = /* @__PURE__ */ new Set();
2618
2852
  for (const exit of objects(answer["exits"])) {
2619
- const target = findEntity(roster, text(exit["to"]), "place");
2853
+ const target = findEntity(roster, text$1(exit["to"]), "place");
2620
2854
  if (target === void 0 || target.key === entity.key) {
2621
- notes.push(`${entity.name}: the way to "${text(exit["to"])}" leads to no place of the world`);
2855
+ notes.push(`${entity.name}: the way to "${text$1(exit["to"])}" leads to no place of the world`);
2622
2856
  continue;
2623
2857
  }
2624
2858
  if (to.has(target.key)) continue;
2625
2859
  to.add(target.key);
2626
2860
  exits.push({
2627
2861
  to: target.key,
2628
- ...text(exit["description"]) === "" ? {} : { description: text(exit["description"]) }
2862
+ ...text$1(exit["description"]) === "" ? {} : { description: text$1(exit["description"]) }
2629
2863
  });
2630
2864
  }
2631
2865
  put(document, "exits", exits.slice(0, 30));
@@ -2671,25 +2905,25 @@ function factionDocument(entity, answer, roster) {
2671
2905
  "summary",
2672
2906
  "description",
2673
2907
  "structure"
2674
- ]) put(document, field, text(answer[field]));
2908
+ ]) put(document, field, text$1(answer[field]));
2675
2909
  put(document, "values", list(answer["values"]));
2676
2910
  const start = {};
2677
- put(start, "public_state", text(answer["public_state"]));
2678
- put(start, "inner_state", text(answer["inner_state"]));
2911
+ put(start, "public_state", text$1(answer["public_state"]));
2912
+ put(start, "inner_state", text$1(answer["inner_state"]));
2679
2913
  put(document, "start", Object.keys(start).length === 0 ? void 0 : start);
2680
2914
  const members = [];
2681
2915
  const seen = /* @__PURE__ */ new Set();
2682
2916
  for (const member of objects(answer["members"])) {
2683
- const character = findEntity(roster, text(member["character"]), "character");
2917
+ const character = findEntity(roster, text$1(member["character"]), "character");
2684
2918
  if (character === void 0) {
2685
- notes.push(`${entity.name}: the member "${text(member["character"])}" is nobody in the world`);
2919
+ notes.push(`${entity.name}: the member "${text$1(member["character"])}" is nobody in the world`);
2686
2920
  continue;
2687
2921
  }
2688
2922
  if (seen.has(character.key)) continue;
2689
2923
  seen.add(character.key);
2690
2924
  members.push({
2691
2925
  character: character.key,
2692
- ...text(member["role"]) === "" ? {} : { role: text(member["role"]) }
2926
+ ...text$1(member["role"]) === "" ? {} : { role: text$1(member["role"]) }
2693
2927
  });
2694
2928
  }
2695
2929
  put(document, "members", members);
@@ -2717,11 +2951,11 @@ function thingDocument(entity, answer, roster) {
2717
2951
  name: entity.name,
2718
2952
  unique: true
2719
2953
  };
2720
- put(document, "description", text(answer["description"]));
2721
- put(document, "quality", text(answer["quality"]));
2954
+ put(document, "description", text$1(answer["description"]));
2955
+ put(document, "quality", text$1(answer["quality"]));
2722
2956
  if (answer["notable"] === true) document["notable"] = true;
2723
- const holder = text(answer["held_by"]) === "" ? void 0 : findEntity(roster, text(answer["held_by"]), "character");
2724
- const place = text(answer["location"]) === "" ? void 0 : findEntity(roster, text(answer["location"]), "place");
2957
+ const holder = text$1(answer["held_by"]) === "" ? void 0 : findEntity(roster, text$1(answer["held_by"]), "character");
2958
+ const place = text$1(answer["location"]) === "" ? void 0 : findEntity(roster, text$1(answer["location"]), "place");
2725
2959
  if (holder !== void 0) document["held_by"] = holder.key;
2726
2960
  else if (place !== void 0) document["location"] = place.key;
2727
2961
  else notes.push(`${entity.name}: it is nowhere in the world and nobody has it, so it is left out`);
@@ -2785,8 +3019,8 @@ const LORE_SUBJECT = {
2785
3019
  };
2786
3020
  function loreDocuments(answer, roster, taken) {
2787
3021
  return objects(answer["entries"]).flatMap((entry) => {
2788
- const title = text(entry["title"]);
2789
- const body = text(entry["body"]);
3022
+ const title = text$1(entry["title"]);
3023
+ const body = text$1(entry["body"]);
2790
3024
  if (title === "" || body === "") return [];
2791
3025
  const notes = [];
2792
3026
  const subjects = [];
@@ -2797,10 +3031,10 @@ function loreDocuments(answer, roster, taken) {
2797
3031
  "place",
2798
3032
  "faction",
2799
3033
  "thing"
2800
- ].includes(text(subject["kind"])) ? text(subject["kind"]) : void 0;
2801
- const found = kind === void 0 ? void 0 : findEntity(roster, text(subject["name"]), kind);
3034
+ ].includes(text$1(subject["kind"])) ? text$1(subject["kind"]) : void 0;
3035
+ const found = kind === void 0 ? void 0 : findEntity(roster, text$1(subject["name"]), kind);
2802
3036
  if (found === void 0) {
2803
- notes.push(`${title}: the subject "${text(subject["name"])}" is not in the world`);
3037
+ notes.push(`${title}: the subject "${text$1(subject["name"])}" is not in the world`);
2804
3038
  continue;
2805
3039
  }
2806
3040
  if (!seen.has(found.key)) {
@@ -2816,7 +3050,7 @@ function loreDocuments(answer, roster, taken) {
2816
3050
  id: uniqueKey(slug(title, "lore"), taken),
2817
3051
  title,
2818
3052
  kind,
2819
- summary: text(entry["summary"]),
3053
+ summary: text$1(entry["summary"]),
2820
3054
  body
2821
3055
  };
2822
3056
  put(document, "subjects", subjects);
@@ -2891,6 +3125,53 @@ function pruneLoreSubjects(result) {
2891
3125
  else entry["subjects"] = kept;
2892
3126
  }
2893
3127
  }
3128
+ /** Takes out of what characters know the places and things that were not written (a thing that is nowhere and nobody's is not made). */
3129
+ function pruneKnowledge(result) {
3130
+ const written = {
3131
+ locations: new Set(result.locations.map((entry) => String(entry["id"]))),
3132
+ items: new Set(result.items.map((entry) => String(entry["id"])))
3133
+ };
3134
+ for (const character of result.characters) {
3135
+ const knowledge = character["knowledge"];
3136
+ if (knowledge === void 0) continue;
3137
+ for (const field of ["locations", "items"]) {
3138
+ const keys = knowledge[field] ?? [];
3139
+ const kept = keys.filter((key) => written[field].has(key));
3140
+ if (kept.length === keys.length) continue;
3141
+ result.notes.push(`${String(character["name"])}: ${keys.length - kept.length} known ${field === "items" ? "thing(s)" : "place(s)"} left out because the world has no such entity`);
3142
+ if (kept.length === 0) delete knowledge[field];
3143
+ else knowledge[field] = kept;
3144
+ }
3145
+ if (Object.keys(knowledge).length === 0) delete character["knowledge"];
3146
+ }
3147
+ }
3148
+ /**
3149
+ * Completes what characters are aware of, because a missing edge means a character does not know the other exists: a character named in someone's relationships
3150
+ * knows of that someone (a neutral acquaintance, added when the character has none), and knows the lore that is about them.
3151
+ */
3152
+ function completeAwareness(result) {
3153
+ const byId = new Map(result.characters.map((character) => [String(character["id"]), character]));
3154
+ let added = 0;
3155
+ for (const character of result.characters) for (const relation of character["relationships"] ?? []) {
3156
+ const other = byId.get(String(relation["to"]));
3157
+ if (other === void 0 || other === character) continue;
3158
+ const theirs = other["relationships"] ?? [];
3159
+ if (theirs.some((entry) => entry["to"] === character["id"])) continue;
3160
+ other["relationships"] = [...theirs, {
3161
+ to: character["id"],
3162
+ label: "acquaintance"
3163
+ }];
3164
+ added += 1;
3165
+ }
3166
+ if (added > 0) result.notes.push(`${added} relationship(s) were added in the other direction as plain acquaintances, so that both characters know of each other`);
3167
+ for (const entry of result.lore) for (const subject of entry["subjects"] ?? []) {
3168
+ const character = subject["kind"] === "character" ? byId.get(String(subject["id"])) : void 0;
3169
+ if (character === void 0) continue;
3170
+ const knowledge = character["knowledge"] ?? (character["knowledge"] = {});
3171
+ const known = knowledge["lore"] ?? [];
3172
+ if (!known.includes(String(entry["id"]))) knowledge["lore"] = [...known, String(entry["id"])];
3173
+ }
3174
+ }
2894
3175
  /** Adds an entry unless the world already has it: the same title, or a body that an earlier entry already contains (a longer one replaces a shorter that it contains). */
2895
3176
  function addLore(lore, entry) {
2896
3177
  const title = norm(String(entry["title"]));
@@ -3027,6 +3308,8 @@ async function extractEntities(ctx, card, items, classified, roster) {
3027
3308
  }
3028
3309
  placeAtScenario(result, items, classified, roster);
3029
3310
  pruneLoreSubjects(result);
3311
+ pruneKnowledge(result);
3312
+ completeAwareness(result);
3030
3313
  return result;
3031
3314
  }
3032
3315
  const STYLE_SCHEMA = {
@@ -3065,21 +3348,24 @@ function styleProblem(id, value) {
3065
3348
  }
3066
3349
  /** Turns the instructions of a card into the prose prompts of the world. Only prose and behaviour are kept: the rules of the game stay the program's. */
3067
3350
  async function extractStyle(ctx, card, items, classified) {
3068
- const pieces = instructionPieces(card, items, classified);
3351
+ return await extractStyleFrom(ctx, card.name, instructionPieces(card, items, classified));
3352
+ }
3353
+ /** The prose prompts that instruction texts become, and what was left out of them. */
3354
+ async function extractStyleFrom(ctx, name, pieces) {
3069
3355
  if (pieces.length === 0) return {
3070
3356
  prompts: [],
3071
3357
  notes: []
3072
3358
  };
3073
3359
  ctx.say("writing the style prompts");
3074
3360
  try {
3075
- const prompt = `Card: ${card.name}\n\nThe instructions of the card:\n\n${pieces.join("\n\n---\n\n").slice(0, SOURCE_BUDGET_CHARS)}`;
3361
+ const prompt = `Card: ${name}\n\nThe instructions of the card:\n\n${pieces.join("\n\n---\n\n").slice(0, SOURCE_BUDGET_CHARS)}`;
3076
3362
  const answer = await ctx.run({
3077
3363
  persona: ctx.text("import/style", { rules: ctx.text("import/common-rules") }),
3078
3364
  prompt,
3079
3365
  result: STYLE_SCHEMA,
3080
- check: (value) => styleProblem("roleplay/style", text(value.narration)) ?? styleProblem("roleplay/character-style", text(value.characters))
3366
+ check: (value) => styleProblem("roleplay/style", text$1(value.narration)) ?? styleProblem("roleplay/character-style", text$1(value.characters))
3081
3367
  });
3082
- const prompts = [["roleplay/style", text(answer.narration)], ["roleplay/character-style", text(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3368
+ const prompts = [["roleplay/style", text$1(answer.narration)], ["roleplay/character-style", text$1(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3083
3369
  id,
3084
3370
  text: body
3085
3371
  }]);
@@ -3215,15 +3501,15 @@ function variableDocuments(answer, roster) {
3215
3501
  const keyOf = (name) => roster.find((entity) => norm(entity.name) === norm(name) || entity.aliases.some((alias) => norm(alias) === norm(name)))?.key;
3216
3502
  const taken = /* @__PURE__ */ new Set();
3217
3503
  return objects(answer["variables"]).map((entry, index) => {
3218
- const base = slug(text(entry["key"]) || text(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
3504
+ const base = slug(text$1(entry["key"]) || text$1(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
3219
3505
  const document = {
3220
3506
  key: uniqueKey(/^[a-z][a-z0-9_]*$/.test(base) ? base : `variable_${index + 1}`, taken),
3221
- name: text(entry["name"]),
3222
- kind: text(entry["kind"]),
3223
- subject: text(entry["subject"])
3507
+ name: text$1(entry["name"]),
3508
+ kind: text$1(entry["kind"]),
3509
+ subject: text$1(entry["subject"])
3224
3510
  };
3225
- put(document, "description", text(entry["description"]));
3226
- put(document, "visibility", text(entry["visibility"]));
3511
+ put(document, "description", text$1(entry["description"]));
3512
+ put(document, "visibility", text$1(entry["visibility"]));
3227
3513
  put(document, "only", list(entry["only"]).flatMap((name) => keyOf(name) ?? []));
3228
3514
  for (const field of ["min", "max"]) if (typeof entry[field] === "number") document[field] = entry[field];
3229
3515
  if (typeof entry["integer"] === "boolean") document["integer"] = entry["integer"];
@@ -3233,9 +3519,9 @@ function variableDocuments(answer, roster) {
3233
3519
  "string"
3234
3520
  ].includes(typeof entry["default"])) document["default"] = entry["default"];
3235
3521
  put(document, "options", list(entry["options"]));
3236
- put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text(band["label"]) !== "").map((band) => ({
3522
+ put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text$1(band["label"]) !== "").map((band) => ({
3237
3523
  up_to: band["up_to"],
3238
- label: text(band["label"])
3524
+ label: text$1(band["label"])
3239
3525
  })));
3240
3526
  return document;
3241
3527
  });
@@ -3736,6 +4022,95 @@ async function loadCalendar(worldDir) {
3736
4022
  return result;
3737
4023
  }
3738
4024
  //#endregion
4025
+ //#region src/host/dice/load.ts
4026
+ const DICE_FILE_NAME = "dice.json";
4027
+ function readBand(band) {
4028
+ const label = band.string("label", { required: true });
4029
+ const result = band.oneOf("result", DICE_RESULTS, "failed");
4030
+ const min = band.number("min");
4031
+ const max = band.number("max");
4032
+ const critical = band.raw("critical");
4033
+ if (critical !== void 0 && critical !== null && typeof critical !== "boolean") band.fail("critical", "must be true or false");
4034
+ if (band.raw("result") === void 0) band.fail("result", `is required: one of ${DICE_RESULTS.join(", ")}`);
4035
+ return label === void 0 ? void 0 : {
4036
+ label,
4037
+ result,
4038
+ ...min === void 0 ? {} : { min },
4039
+ ...max === void 0 ? {} : { max },
4040
+ ...critical === true ? { critical: true } : {}
4041
+ };
4042
+ }
4043
+ /**
4044
+ * Read `dice.json`: the checks a world settles uncertain attempts with (docs/world-format.md). The dice and how their result is read are the world's:
4045
+ * the game master rolls a check and is told the band the roll fell in, never a number to interpret.
4046
+ */
4047
+ function parseDiceFile(text) {
4048
+ const issues = [];
4049
+ const reader = Reader.fromJson(text, issues);
4050
+ if (reader === void 0) return {
4051
+ ok: false,
4052
+ issues
4053
+ };
4054
+ const checks = reader.objects("checks").flatMap((entry) => {
4055
+ const key = entry.string("key", { required: true });
4056
+ const name = entry.string("name", { required: true });
4057
+ const use = entry.string("use", { required: true });
4058
+ const dice = entry.string("dice", { required: true });
4059
+ const reading = entry.oneOf("reading", DICE_READINGS, "total");
4060
+ const compare = entry.oneOf("compare", DICE_COMPARISONS, "absolute");
4061
+ const hit = entry.number("hit", { min: 1 });
4062
+ const modifier = entry.string("modifier");
4063
+ const bands = entry.objects("bands").flatMap((band) => {
4064
+ const read = readBand(band);
4065
+ return read === void 0 ? [] : [read];
4066
+ });
4067
+ if (key === void 0 || name === void 0 || use === void 0 || dice === void 0) return [];
4068
+ const definition = {
4069
+ key,
4070
+ name,
4071
+ use,
4072
+ dice,
4073
+ reading,
4074
+ compare,
4075
+ bands,
4076
+ ...hit === void 0 ? {} : { hit },
4077
+ ...modifier === void 0 || modifier === "" ? {} : { modifier }
4078
+ };
4079
+ for (const problem of checkProblems(definition)) entry.fail("", problem);
4080
+ return [definition];
4081
+ });
4082
+ const seen = /* @__PURE__ */ new Set();
4083
+ for (const check of checks) {
4084
+ if (seen.has(check.key)) reader.fail("checks", `the key "${check.key}" is used by more than one check`);
4085
+ seen.add(check.key);
4086
+ }
4087
+ if (checks.length > 40) reader.fail("checks", `a world has at most 40 checks`);
4088
+ return issues.length > 0 ? {
4089
+ ok: false,
4090
+ issues
4091
+ } : {
4092
+ ok: true,
4093
+ value: checks
4094
+ };
4095
+ }
4096
+ /** The checks of a world: an optional `<world>/dice.json`; a world without one has none, and its game master rolls plain dice only. */
4097
+ async function loadDice(worldDir) {
4098
+ const result = {
4099
+ checks: [],
4100
+ problems: []
4101
+ };
4102
+ const file = join(worldDir, DICE_FILE_NAME);
4103
+ try {
4104
+ result.checks = await readDocument(file, parseDiceFile, result.problems) ?? [];
4105
+ } catch (error) {
4106
+ if (error.code !== "ENOENT") result.problems.push({
4107
+ path: file,
4108
+ message: errorMessage(error)
4109
+ });
4110
+ }
4111
+ return result;
4112
+ }
4113
+ //#endregion
3739
4114
  //#region src/host/triggers/load.ts
3740
4115
  const TRIGGERS_FILE_NAME = "triggers.json";
3741
4116
  /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
@@ -3911,6 +4286,10 @@ function routineProblems(characters, locations, calendar = {
3911
4286
  return [];
3912
4287
  }));
3913
4288
  }
4289
+ /** Keeps the checks of the world with the story: what its game master rolls and how the dice are read. */
4290
+ function populateDice(session, checks) {
4291
+ for (const check of checks) session.dice.define(check);
4292
+ }
3914
4293
  /** Keeps the world's calendar with the story, for the days a routine or a trigger waits for. */
3915
4294
  function populateCalendar(session, calendar) {
3916
4295
  if (calendar.holidays.length > 0 || calendar.hemisphere !== "north") writeCalendar(session.metadata, calendar);
@@ -4183,6 +4562,8 @@ async function loadValidatedWorld(world) {
4183
4562
  })));
4184
4563
  const { calendar, problems: calendarProblems } = await loadCalendar(world.directory);
4185
4564
  if (calendarProblems.length > 0) throw new InvalidWorldError(`the calendar of "${world.summary.name}" has ${calendarProblems.length} problem(s)`, calendarProblems);
4565
+ const dice = await loadDice(world.directory);
4566
+ if (dice.problems.length > 0) throw new InvalidWorldError(`the dice checks of "${world.summary.name}" have ${dice.problems.length} problem(s)`, dice.problems);
4186
4567
  const days = routineProblems(characters, locations, calendar);
4187
4568
  if (days.length > 0) throw new InvalidWorldError(`the days of the characters of "${world.summary.name}" have ${days.length} problem(s)`, days.map((message) => ({
4188
4569
  path: world.directory,
@@ -4253,7 +4634,8 @@ async function loadValidatedWorld(world) {
4253
4634
  declared,
4254
4635
  scripted,
4255
4636
  authoredPlots,
4256
- calendar
4637
+ calendar,
4638
+ checks: dice.checks
4257
4639
  };
4258
4640
  }
4259
4641
  //#endregion
@@ -5907,6 +6289,109 @@ function translateTools(worlds, settings, prompting) {
5907
6289
  })];
5908
6290
  }
5909
6291
  //#endregion
6292
+ //#region src/host/import/preset.ts
6293
+ /** The older preset layout keeps its texts under fixed keys. */
6294
+ const LEGACY_KEYS = [
6295
+ "main_prompt",
6296
+ "nsfw_prompt",
6297
+ "jailbreak_prompt",
6298
+ "impersonation_prompt",
6299
+ "new_chat_prompt",
6300
+ "new_group_chat_prompt",
6301
+ "new_example_chat_prompt"
6302
+ ];
6303
+ const MAX_PIECES = 60;
6304
+ const MAX_PIECE_CHARS = 8e3;
6305
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6306
+ const text = (value) => typeof value === "string" ? value.trim() : "";
6307
+ /** The order the preset sends its prompts in: the longest list it gives, with what each entry says about being on. */
6308
+ function orderOf(root) {
6309
+ return ((Array.isArray(root["prompt_order"]) ? root["prompt_order"].flatMap((entry) => isObject(entry) && Array.isArray(entry["order"]) ? [entry["order"]] : []) : []).sort((a, b) => b.length - a.length)[0] ?? []).flatMap((entry) => isObject(entry) && typeof entry["identifier"] === "string" ? [{
6310
+ identifier: entry["identifier"],
6311
+ enabled: entry["enabled"] !== false
6312
+ }] : []);
6313
+ }
6314
+ /**
6315
+ * Reads a preset file. Markers (places where chat history or the card's fields are inserted), switched-off prompts and empty ones are left out.
6316
+ * @throws {ImportCardError} when the file is not a preset, with why.
6317
+ */
6318
+ function readPreset(file, name) {
6319
+ let root;
6320
+ try {
6321
+ root = JSON.parse(file.toString("utf8").replace(/^/, ""));
6322
+ } catch {
6323
+ throw new ImportCardError("the file is not JSON: a preset is the .json file SillyTavern exports");
6324
+ }
6325
+ if (!isObject(root)) throw new ImportCardError("the file is not a preset: it must be a JSON object");
6326
+ const pieces = [];
6327
+ const prompts = Array.isArray(root["prompts"]) ? root["prompts"].filter(isObject) : [];
6328
+ if (prompts.length > 0) {
6329
+ const byId = new Map(prompts.flatMap((prompt) => typeof prompt["identifier"] === "string" ? [[prompt["identifier"], prompt]] : []));
6330
+ const ordered = orderOf(root);
6331
+ const chosen = ordered.length > 0 ? ordered.flatMap((entry) => entry.enabled && byId.has(entry.identifier) ? [byId.get(entry.identifier)] : []) : prompts.filter((prompt) => prompt["enabled"] !== false);
6332
+ for (const prompt of chosen) {
6333
+ const content = text(prompt["content"]);
6334
+ if (prompt["marker"] === true || content === "") continue;
6335
+ const title = text(prompt["name"]);
6336
+ pieces.push(`${title === "" ? "" : `[${title}]\n`}${content.slice(0, MAX_PIECE_CHARS)}`);
6337
+ }
6338
+ } else for (const key of LEGACY_KEYS) if (text(root[key]) !== "") pieces.push(`[${key}]\n${text(root[key]).slice(0, MAX_PIECE_CHARS)}`);
6339
+ if (pieces.length === 0) throw new ImportCardError("the file holds no instructions this importer can read: a preset has a \"prompts\" list with texts in it");
6340
+ const title = text(root["name"]) || text(root["preset_name"]);
6341
+ return {
6342
+ name: title === "" ? name.replace(/\.json$/i, "") : title,
6343
+ pieces: pieces.slice(0, MAX_PIECES)
6344
+ };
6345
+ }
6346
+ //#endregion
6347
+ //#region src/host/import/preset-tools.ts
6348
+ const PRESET_TOOL = "import_preset";
6349
+ const PRESET_FILE = "preset.json";
6350
+ const PRESET_PATH = `${IMPORT_FOLDER}/${PRESET_FILE}`;
6351
+ /** The command that has the authoring chat apply a preset that was uploaded to the world. */
6352
+ const presetMessage = () => `Apply the narration preset I uploaded to this world: call ${PRESET_TOOL} with file ${PRESET_PATH}.`;
6353
+ /** The tool that turns an uploaded narration preset into the world's prose prompts; every call asks the person first. */
6354
+ function presetTools(worlds, settings, prompting) {
6355
+ return [defineTool({
6356
+ name: PRESET_TOOL,
6357
+ description: `Turn the narration preset the person uploaded to this world (${PRESET_PATH}) into the world's prose prompts: how the narration is written and how the characters speak and behave. Rules of the game, formats and scripts in the preset are not carried. It replaces the world's own versions of those prompts, so the person is asked first.`,
6358
+ parameters: { file: {
6359
+ type: "string",
6360
+ required: true,
6361
+ description: `The preset: ${PRESET_PATH}.`
6362
+ } },
6363
+ output: {
6364
+ schema: { type: "json" },
6365
+ render: (_args, value) => [{
6366
+ type: "text",
6367
+ text: JSON.stringify(value, null, 1)
6368
+ }]
6369
+ },
6370
+ isConcurrencySafe: () => false,
6371
+ async execute(args, exec) {
6372
+ if (args.file.trim() !== PRESET_PATH) throw new Error(`the preset is ${PRESET_PATH}`);
6373
+ const world = await worldOf(worlds, exec);
6374
+ const file = join(world.directory, IMPORT_FOLDER, PRESET_FILE);
6375
+ const preset = readPreset(await readFile(file).catch(() => {
6376
+ throw new Error("no preset was uploaded to this world");
6377
+ }), "preset");
6378
+ const language = prompting.languages().get(world.id);
6379
+ const text = (id, variables) => prompting.prompts().text(id, language, variables);
6380
+ const made = await extractStyleFrom(contextOf(exec, settings(), text), preset.name, preset.pieces);
6381
+ for (const { id, text: body } of made.prompts) for (const tag of shippedLanguages()) await writeWorldPrompt(world.directory, tag, id, withPlayer(body));
6382
+ await rm(file, { force: true });
6383
+ const written = made.prompts.map((entry) => entry.id);
6384
+ return JSON.parse(JSON.stringify({
6385
+ preset: preset.name,
6386
+ written,
6387
+ folder: `${PROMPTS_FOLDER}/<language>/`,
6388
+ notes: made.notes,
6389
+ next: written.length === 0 ? "Nothing in the preset was about how to write the story, so no prompt was changed: tell the person." : "Tell the person which prompts were written (they can read and edit them in the world's Prompts section) and what was not carried over."
6390
+ }));
6391
+ }
6392
+ })];
6393
+ }
6394
+ //#endregion
5910
6395
  //#region src/host/triggers/parts.ts
5911
6396
  /** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
5912
6397
  async function loadWorldParts(directory) {
@@ -6871,6 +7356,6 @@ async function deleteAuthoredEntity(world, kind, key) {
6871
7356
  return destination;
6872
7357
  }
6873
7358
  //#endregion
6874
- export { subfolders as $, isReviewing as A, populateLore as B, translateTools as C, parseThingEdit as Ct, authoringChatSessionId as D, authoredWorldOf as E, populateClock as F, TRIGGERS_FILE_NAME as G, populateTriggers as H, populateFactions as I, parseCalendarFile as J, CALENDAR_FILE_NAME as K, populateItems as L, loadValidatedWorld as M, populateCalendar as N, languageOfDocuments as O, populateCharacters as P, loadCharacters as Q, populateKnowledge as R, translateMessage as S, parseRelationEdit as St, importTools as T, populateVariables as U, populateRoutines as V, routineProblems as W, loadItems as X, loadLocations as Y, CHARACTERS_DIR as Z, replaceFile$1 as _, InvalidEditProblems as _t, replaceAuthoredEntity as a, VARIABLES_FILE_NAME as at, triggerProblemsOf as b, parseLoreEdit as bt, editWorldLore as c, CHARACTER_FILE_NAME as ct, editWorldPlots as d, ImportNotFoundError as dt, PROSE_PROMPTS as et, editWorldRelation as f, ImportStore as ft, readWorldEditor as g, parseWorldInfoEdit as gt, generateWorldCharacterPortrait as h, parseWorldFile as ht, readAuthoredEntityDocument as i, writeWorldPrompt as it, markReady as j, readWorldDocuments as k, editWorldNarrationVoice as l, parseCharacterFile as lt, entityFolder as m, WORLD_FILE_NAME as mt, createAuthoredEntity as n, listWorldPrompts as nt, editWorldCharacter as o, parseVariablesFile as ot, editWorldThing as p, parseChoices as pt, loadCalendar as q, deleteAuthoredEntity as r, readWorldPrompt as rt, editWorldFaction as s, variableProblems as st, AUTHORED_ENTITY_KINDS as t, deleteWorldPrompt as tt, editWorldPlace as u, IMPORT_FOLDER as ut, uploadWorldCharacterPortrait as v, parseCharacterEdit as vt, importHooks as w, IMPORT_COMMAND as wt, loadWorldParts as x, parsePlaceEdit as xt, worldCharacterPortraitFile as y, parseFactionEdit as yt, populateLocations as z };
7359
+ export { parseDiceFile as $, authoredWorldOf as A, parsePlaceEdit as At, populateDice as B, DICE_RESULTS as Bt, presetMessage as C, WORLD_FILE_NAME as Ct, translateTools as D, parseCharacterEdit as Dt, translateMessage as E, InvalidEditProblems as Et, markReady as F, isPng as Ft, populateLore as G, populateItems as H, loadValidatedWorld as I, pictureOf as It, populateVariables as J, populateRoutines as K, populateCalendar as L, readCard as Lt, languageOfDocuments as M, parseThingEdit as Mt, readWorldDocuments as N, IMPORT_COMMAND as Nt, importHooks as O, parseFactionEdit as Ot, isReviewing as P, ImportCardError as Pt, loadDice as Q, populateCharacters as R, DICE_COMPARISONS as Rt, PRESET_FILE as S, parseChoices as St, readPreset as T, parseWorldInfoEdit as Tt, populateKnowledge as U, populateFactions as V, populateLocations as W, TRIGGERS_FILE_NAME as X, routineProblems as Y, DICE_FILE_NAME as Z, replaceFile$1 as _, CHARACTER_FILE_NAME as _t, replaceAuthoredEntity as a, CHARACTERS_DIR as at, triggerProblemsOf as b, ImportNotFoundError as bt, editWorldLore as c, PROSE_PROMPTS as ct, editWorldPlots as d, readWorldPrompt as dt, CALENDAR_FILE_NAME as et, editWorldRelation as f, writeWorldPrompt as ft, readWorldEditor as g, variableProblems as gt, generateWorldCharacterPortrait as h, parseVariablesFile as ht, readAuthoredEntityDocument as i, loadItems as it, authoringChatSessionId as j, parseRelationEdit as jt, importTools as k, parseLoreEdit as kt, editWorldNarrationVoice as l, deleteWorldPrompt as lt, entityFolder as m, loadVariables as mt, createAuthoredEntity as n, parseCalendarFile as nt, editWorldCharacter as o, loadCharacters as ot, editWorldThing as p, VARIABLES_FILE_NAME as pt, populateTriggers as q, deleteAuthoredEntity as r, loadLocations as rt, editWorldFaction as s, subfolders as st, AUTHORED_ENTITY_KINDS as t, loadCalendar as tt, editWorldPlace as u, listWorldPrompts as ut, uploadWorldCharacterPortrait as v, parseCharacterFile as vt, presetTools as w, parseWorldFile as wt, loadWorldParts as x, ImportStore as xt, worldCharacterPortraitFile as y, IMPORT_FOLDER as yt, populateClock as z, DICE_READINGS as zt };
6875
7360
 
6876
- //# sourceMappingURL=documents-DtlY2IRt.js.map
7361
+ //# sourceMappingURL=documents-Do4lz4SB.js.map