@dsh-agentic-roleplay/core 0.8.1 → 0.9.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 (51) hide show
  1. package/lib/{access-DtOxFKBK.js → access-CfQWbNZP.js} +4 -7
  2. package/lib/{authoring-tools-DNnx0Nts.js → authoring-tools-CdHlvx32.js} +2125 -152
  3. package/lib/authoring.js +143 -47
  4. package/lib/{child-D6mpkkCE.js → child-lYYeOwl2.js} +28 -51
  5. package/lib/client.js +611 -774
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +8 -13
  8. package/lib/{doctor-chat-ByDfCMeo.js → doctor-chat-hL1a61hp.js} +2 -3
  9. package/lib/doctor.js +6 -8
  10. package/lib/{gallery-D9nG3C78.js → gallery-BKh7eu80.js} +3 -4
  11. package/lib/{generator-r1Czm7oi.js → generator-DdZ1-sgv.js} +3 -4
  12. package/lib/helper.js +2 -3
  13. package/lib/{hooks-BQCzgggH.js → hooks-CcQj_dJo.js} +69 -97
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +195 -265
  16. package/lib/{library-zI-2tG7h.js → library-QFL6Z_Nr.js} +9 -15
  17. package/lib/{lorebook-author-tools-ywaYicwd.js → lorebook-author-tools-DWBnYo1E.js} +10 -13
  18. package/lib/lorebook-authoring.js +5 -6
  19. package/lib/{narration-CnBlVure.js → narration-CjB_KwwY.js} +9 -15
  20. package/lib/orchestration.js +53 -64
  21. package/lib/{pack-jail-5EJ-WYyW.js → pack-jail-BMy6NcCY.js} +81 -788
  22. package/lib/{packs-Cv8hanXJ.js → packs-BREPSfHy.js} +6 -10
  23. package/lib/{presenter-agent-BSaMSd3G.js → presenter-agent-B49-_iUm.js} +12 -18
  24. package/lib/{preset-CWI3-0r1.js → preset-BqgY1Tz4.js} +5 -6
  25. package/lib/{preset-author-tools-BrJYa2cr.js → preset-author-tools-BB_Dcv2o.js} +12 -14
  26. package/lib/preset-authoring.js +6 -7
  27. package/lib/{presets-MwOSMMyu.js → presets-Bwnrx7p0.js} +69 -63
  28. package/lib/{reflection-zSaMsjKj.js → reflection-CUWG-6Qg.js} +19 -30
  29. package/lib/{text-BzudpQLS.js → text-CbGQhK1-.js} +9 -10
  30. package/lib/{turn-guard-Cv8pfHEA.js → turn-guard-Bb8Ew-1z.js} +6 -11
  31. package/package.json +29 -29
  32. package/prompts/en/checks/decide-sheet.md +1 -0
  33. package/prompts/en/checks/fidelity.md +7 -0
  34. package/prompts/en/checks/gaps.md +4 -0
  35. package/prompts/en/checks/notice.md +3 -0
  36. package/prompts/en/import/casting.md +1 -1
  37. package/prompts/en/import/character.md +1 -0
  38. package/prompts/en/import/finish-draft.md +1 -1
  39. package/prompts/en/import/finish-ok.md +3 -1
  40. package/prompts/en/import/notice-repair.md +2 -2
  41. package/prompts/en/import/repair-again.md +2 -2
  42. package/prompts/zh/checks/decide-sheet.md +1 -0
  43. package/prompts/zh/checks/fidelity.md +7 -0
  44. package/prompts/zh/checks/gaps.md +4 -0
  45. package/prompts/zh/checks/notice.md +3 -0
  46. package/prompts/zh/import/casting.md +1 -1
  47. package/prompts/zh/import/character.md +1 -0
  48. package/prompts/zh/import/finish-draft.md +1 -1
  49. package/prompts/zh/import/finish-ok.md +3 -1
  50. package/prompts/zh/import/notice-repair.md +2 -2
  51. package/prompts/zh/import/repair-again.md +2 -2
@@ -1,24 +1,25 @@
1
- import "./access-DtOxFKBK.js";
2
- import { A as isLeftOut, At as DEFAULT_SLOTS, C as pruneMembers, D as classifyItems, Dt as LORE_KINDS, E as buildRoster, G as withPlayer, H as cleanText, K as IMPORT_FOLDER, M as askYesNo, Ot as LORE_SCOPES, Q as readImportFolder, S as pruneLoreSubjects, U as itemise, X as openingText, Y as PICTURE_FILE, _ as extractStyle, _t as parseCharacterFile, a as isPresetName, at as variableProblems, b as pruneKnowledge, bt as InvalidEditProblems, ct as LOCATION_FILE_NAME, dt as SLOTS_FILE_NAME, ft as parseItemFile, g as extractEntities, gt as CHARACTER_FILE_NAME, h as emptyExtracted, ht as parseFactionFile, k as ROLES, kt as WEEKDAY_NAMES, lt as parseLocationFile, mt as FACTION_FILE_NAME, nt as VARIABLES_FILE_NAME, ot as LORE_FILE_NAME, pt as parseSlotsFile, rt as loadVariables, st as parseLoreFile, tt as parseImportCommand, ut as ITEM_FILE_NAME, vt as readVariableValues, w as pruneRelationships, x as pruneLinks, y as extractVariables, yt as readIdentifier } from "./presets-MwOSMMyu.js";
3
- import { l as atomicWrite, m as parseSwitchboard, u as atomicWriteJson } from "./narration-CnBlVure.js";
4
- import { G as commandFlagKey, K as readDocument, U as plotReferenceProblems, V as loadPlots, Y as errorMessage, Z as PROMPTS_FOLDER, a as externalWithheld, it as shippedLanguages, lt as InvalidWorldError, q as Reader, r as externalGiven, rt as promptProblem, t as externalToolLimit } from "./hooks-BQCzgggH.js";
5
- import { t as trimCharacters } from "./text-BzudpQLS.js";
6
- import { c as runChild, h as currentTurn, s as namedModel, t as ChildTimeoutError, u as parseSampling } from "./child-D6mpkkCE.js";
7
- import { C as trOf, _ as writeImageFileMetadata, b as mapLimit, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as uniqueKey, x as norm } from "./library-zI-2tG7h.js";
1
+ import "./access-CfQWbNZP.js";
2
+ import { A as sourcesFor, B as noAt, C as inert, Ct as CHARACTER_FILE_NAME, D as pruneLoreSubjects, Dt as InvalidEditProblems, E as pruneLinks, Et as readIdentifier, F as isLeftOut, Ft as LORE_SCOPES, H as yesAt, It as WEEKDAY_NAMES, J as cleanText, L as askYesNo, Lt as DEFAULT_SLOTS, M as classifyItems, N as findEntity, O as pruneMembers, P as ROLES, Pt as LORE_KINDS, Q as IMPORT_FOLDER, S as extractVariables, St as parseFactionFile, T as pruneKnowledge, Tt as readVariableValues, Y as itemise, Z as withPlayer, _ as characterDocument, _t as ITEM_FILE_NAME, a as isPresetName, b as extractStyle, bt as parseSlotsFile, ft as variableProblems, g as asWritten, gt as parseLocationFile, h as addLore, ht as LOCATION_FILE_NAME, it as readImportFolder, j as buildRoster, k as pruneRelationships, lt as VARIABLES_FILE_NAME, mt as parseLoreFile, nt as openingText, pt as LORE_FILE_NAME, st as parseImportCommand, tt as PICTURE_FILE, ut as loadVariables, v as emptyExtracted, vt as SLOTS_FILE_NAME, w as loreDocuments, wt as parseCharacterFile, xt as FACTION_FILE_NAME, y as extractEntities, yt as parseItemFile } from "./presets-Bwnrx7p0.js";
3
+ import { l as atomicWrite, m as parseSwitchboard, u as atomicWriteJson } from "./narration-CjB_KwwY.js";
4
+ import { $ as copyWorldPrompts, B as loadPlots, H as plotReferenceProblems, J as formatIssue, K as readDocument$1, W as commandFlagKey, Y as errorMessage, Z as PROMPTS_FOLDER, a as externalWithheld, ht as COMPARISONS, it as shippedLanguages, lt as InvalidWorldError, nt as listFiles, ot as shippedText, q as Reader, r as externalGiven, rt as promptProblem, t as externalToolLimit } from "./hooks-CcQj_dJo.js";
5
+ import { t as trimCharacters } from "./text-CbGQhK1-.js";
6
+ import { c as runChild, h as currentTurn, s as namedModel, t as ChildTimeoutError, u as parseSampling } from "./child-lYYeOwl2.js";
7
+ import { C as trOf, S as slug, _ as writeImageFileMetadata, b as mapLimit, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as uniqueKey, x as norm } from "./library-QFL6Z_Nr.js";
8
8
  import { dirname, join, relative } from "node:path";
9
9
  import { existsSync, readFileSync } from "node:fs";
10
10
  import { createHash } from "node:crypto";
11
- import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
11
+ import { mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
12
12
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
13
13
  import { inflateSync } from "node:zlib";
14
14
  import { defineTool } from "@deepseek-ai/dsh-tools";
15
15
  import { Service } from "@deepseek-ai/cordis";
16
- import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
16
+ import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, lintWorld, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
17
17
  import { lookup } from "node:dns";
18
18
  import { request } from "node:http";
19
19
  import { request as request$1 } from "node:https";
20
20
  import { BlockList, isIP } from "node:net";
21
- //#region src/shared/authoring-chat.ts
21
+ import { tmpdir } from "node:os";
22
+ // src/shared/authoring-chat.ts
22
23
  const PREFIX = "world-author-";
23
24
  /** Stable DSH chat identity for the authoring conversation of one world. */
24
25
  function authoringChatSessionId(worldId) {
@@ -35,18 +36,7 @@ function authoredWorldOf(chatSessionId) {
35
36
  return;
36
37
  }
37
38
  }
38
- //#endregion
39
- //#region ../dsh-roleplay-model/src/trigger.ts
40
- const COMPARISONS = [
41
- "eq",
42
- "ne",
43
- "lt",
44
- "le",
45
- "gt",
46
- "ge"
47
- ];
48
- //#endregion
49
- //#region ../dsh-roleplay-model/src/dice.ts
39
+ // ../dsh-roleplay-model/src/dice.ts
50
40
  /** What a band of a check makes of an attempt; the same three results a round's outcome has. */
51
41
  const DICE_RESULTS = [
52
42
  "succeeded",
@@ -64,8 +54,7 @@ const DICE_COMPARISONS = [
64
54
  "over",
65
55
  "under"
66
56
  ];
67
- //#endregion
68
- //#region src/host/import/card.ts
57
+ // src/host/import/card.ts
69
58
  /** The file is not a character card this importer reads. The message says why, for the person who uploaded it. */
70
59
  var ImportCardError = class extends Error {};
71
60
  const PNG_SIGNATURE = Buffer.from([
@@ -102,7 +91,7 @@ function chunksOf(file) {
102
91
  return chunks;
103
92
  }
104
93
  /** The keyword and text of a PNG text chunk. */
105
- function textOf(chunk) {
94
+ function textOf$1(chunk) {
106
95
  const end = chunk.data.indexOf(0);
107
96
  if (end < 0) return void 0;
108
97
  const keyword = chunk.data.toString("latin1", 0, end);
@@ -134,7 +123,7 @@ function jsonOf(file, name) {
134
123
  const found = /* @__PURE__ */ new Map();
135
124
  for (const chunk of chunksOf(file)) {
136
125
  if (!TEXT_CHUNKS.has(chunk.type)) continue;
137
- const text = textOf(chunk);
126
+ const text = textOf$1(chunk);
138
127
  if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
139
128
  }
140
129
  const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
@@ -168,7 +157,7 @@ function urlsOf(value) {
168
157
  return [...found];
169
158
  }
170
159
  const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
171
- const text = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
160
+ const text$1 = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
172
161
  const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
173
162
  function entryOf(value, index) {
174
163
  const entry = object(value);
@@ -176,10 +165,10 @@ function entryOf(value, index) {
176
165
  const position = entry["position"];
177
166
  return {
178
167
  id: `entry:${index}`,
179
- title: text(entry["comment"]).trim() || text(entry["name"]).trim(),
168
+ title: text$1(entry["comment"]).trim() || text$1(entry["name"]).trim(),
180
169
  keys: texts(entry["keys"]),
181
170
  secondaryKeys: texts(entry["secondary_keys"]),
182
- content: text(entry["content"]),
171
+ content: text$1(entry["content"]),
183
172
  enabled: entry["enabled"] !== false,
184
173
  constant: entry["constant"] === true,
185
174
  selective: entry["selective"] === true,
@@ -194,10 +183,10 @@ function entryOf(value, index) {
194
183
  function readCard(file, name) {
195
184
  const root = object(jsonOf(file, name));
196
185
  const spec = root === void 0 ? void 0 : root["spec"];
197
- 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(spec)}" card: only V2 and V3 cards are read`);
186
+ 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$1(spec)}" card: only V2 and V3 cards are read`);
198
187
  const data = object(root?.["data"]);
199
188
  if (data === void 0) throw new ImportCardError(`${name} has no card data`);
200
- const cardName = text(data["name"]).trim();
189
+ const cardName = text$1(data["name"]).trim();
201
190
  if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
202
191
  const book = object(data["character_book"]);
203
192
  const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
@@ -206,21 +195,21 @@ function readCard(file, name) {
206
195
  return {
207
196
  sourceSpec: spec,
208
197
  name: cardName,
209
- description: text(data["description"]),
210
- personality: text(data["personality"]),
211
- scenario: text(data["scenario"]),
212
- firstMessage: text(data["first_mes"]),
198
+ description: text$1(data["description"]),
199
+ personality: text$1(data["personality"]),
200
+ scenario: text$1(data["scenario"]),
201
+ firstMessage: text$1(data["first_mes"]),
213
202
  alternateGreetings: texts(data["alternate_greetings"]),
214
- messageExample: text(data["mes_example"]),
215
- creatorNotes: text(data["creator_notes"]),
216
- systemPrompt: text(data["system_prompt"]),
217
- postHistoryInstructions: text(data["post_history_instructions"]),
203
+ messageExample: text$1(data["mes_example"]),
204
+ creatorNotes: text$1(data["creator_notes"]),
205
+ systemPrompt: text$1(data["system_prompt"]),
206
+ postHistoryInstructions: text$1(data["post_history_instructions"]),
218
207
  tags: texts(data["tags"]),
219
- creator: text(data["creator"]),
220
- characterVersion: text(data["character_version"]),
208
+ creator: text$1(data["creator"]),
209
+ characterVersion: text$1(data["character_version"]),
221
210
  ...book === void 0 ? {} : { book: {
222
- name: text(book["name"]),
223
- description: text(book["description"]),
211
+ name: text$1(book["name"]),
212
+ description: text$1(book["description"]),
224
213
  entries
225
214
  } },
226
215
  ignored: {
@@ -237,8 +226,7 @@ function readCard(file, name) {
237
226
  }
238
227
  /** Whether a file looks like a PNG, so that its picture can be kept. */
239
228
  const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
240
- //#endregion
241
- //#region src/host/import/output-ceiling.ts
229
+ // src/host/import/output-ceiling.ts
242
230
  /** A share of the model's context window, and the least and the fallback when the window is not known: the default of what one helper request may write. */
243
231
  const AUTO_OUTPUT_SHARE = .1;
244
232
  const AUTO_OUTPUT_MIN = 16e3;
@@ -274,8 +262,7 @@ async function outputCeiling(configured, agent, named, signal) {
274
262
  }
275
263
  return autoOutputCeiling(window);
276
264
  }
277
- //#endregion
278
- //#region src/host/folders.ts
265
+ // src/host/folders.ts
279
266
  /**
280
267
  * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
281
268
  * and a missing directory has none; any other failure is thrown.
@@ -288,8 +275,7 @@ async function subfolders(dir) {
288
275
  throw error;
289
276
  }
290
277
  }
291
- //#endregion
292
- //#region src/host/characters/load.ts
278
+ // src/host/characters/load.ts
293
279
  const CHARACTERS_DIR = "characters";
294
280
  /**
295
281
  * Read the cast of one world: every subfolder of `<world>/characters/` that
@@ -316,7 +302,7 @@ async function loadCharacters(worldDir) {
316
302
  for (const folder of folders) {
317
303
  const file = join(dir, folder, CHARACTER_FILE_NAME);
318
304
  try {
319
- const character = await readDocument(file, (text) => parseCharacterFile(text, folder), result.problems);
305
+ const character = await readDocument$1(file, (text) => parseCharacterFile(text, folder), result.problems);
320
306
  if (character === void 0) continue;
321
307
  const owner = folderById.get(character.id);
322
308
  if (owner !== void 0) {
@@ -337,8 +323,7 @@ async function loadCharacters(worldDir) {
337
323
  }
338
324
  return result;
339
325
  }
340
- //#endregion
341
- //#region src/host/calendar/load.ts
326
+ // src/host/calendar/load.ts
342
327
  const CALENDAR_FILE_NAME = "calendar.json";
343
328
  const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
344
329
  /**
@@ -392,7 +377,7 @@ async function loadCalendar(worldDir) {
392
377
  };
393
378
  const file = join(worldDir, CALENDAR_FILE_NAME);
394
379
  try {
395
- result.calendar = await readDocument(file, parseCalendarFile, result.problems) ?? result.calendar;
380
+ result.calendar = await readDocument$1(file, parseCalendarFile, result.problems) ?? result.calendar;
396
381
  } catch (error) {
397
382
  if (error.code !== "ENOENT") result.problems.push({
398
383
  path: file,
@@ -401,8 +386,7 @@ async function loadCalendar(worldDir) {
401
386
  }
402
387
  return result;
403
388
  }
404
- //#endregion
405
- //#region src/host/commands/load.ts
389
+ // src/host/commands/load.ts
406
390
  const COMMANDS_FILE_NAME = "commands.json";
407
391
  /** The words the game itself uses after a slash. */
408
392
  const RESERVED = /* @__PURE__ */ new Set(["ooc", "roll"]);
@@ -466,7 +450,7 @@ async function loadCommands(worldDir) {
466
450
  };
467
451
  const file = join(worldDir, COMMANDS_FILE_NAME);
468
452
  try {
469
- result.commands = await readDocument(file, parseCommandsFile, result.problems) ?? [];
453
+ result.commands = await readDocument$1(file, parseCommandsFile, result.problems) ?? [];
470
454
  } catch (error) {
471
455
  if (error.code !== "ENOENT") result.problems.push({
472
456
  path: file,
@@ -475,8 +459,7 @@ async function loadCommands(worldDir) {
475
459
  }
476
460
  return result;
477
461
  }
478
- //#endregion
479
- //#region src/host/dice/load.ts
462
+ // src/host/dice/load.ts
480
463
  const DICE_FILE_NAME = "dice.json";
481
464
  function readBand(band) {
482
465
  const label = band.string("label", { required: true });
@@ -555,7 +538,7 @@ async function loadDice(worldDir) {
555
538
  };
556
539
  const file = join(worldDir, DICE_FILE_NAME);
557
540
  try {
558
- result.checks = await readDocument(file, parseDiceFile, result.problems) ?? [];
541
+ result.checks = await readDocument$1(file, parseDiceFile, result.problems) ?? [];
559
542
  } catch (error) {
560
543
  if (error.code !== "ENOENT") result.problems.push({
561
544
  path: file,
@@ -564,8 +547,7 @@ async function loadDice(worldDir) {
564
547
  }
565
548
  return result;
566
549
  }
567
- //#endregion
568
- //#region src/host/factions/load.ts
550
+ // src/host/factions/load.ts
569
551
  const FACTIONS_DIR = "factions";
570
552
  async function loadFactions(worldDir) {
571
553
  const dir = join(worldDir, FACTIONS_DIR);
@@ -587,7 +569,7 @@ async function loadFactions(worldDir) {
587
569
  for (const folder of folders) {
588
570
  const file = join(dir, folder, FACTION_FILE_NAME);
589
571
  try {
590
- const faction = await readDocument(file, (text) => parseFactionFile(text, folder), result.problems);
572
+ const faction = await readDocument$1(file, (text) => parseFactionFile(text, folder), result.problems);
591
573
  if (faction === void 0) continue;
592
574
  const owner = owners.get(faction.id);
593
575
  if (owner !== void 0) {
@@ -612,8 +594,7 @@ async function loadFactions(worldDir) {
612
594
  });
613
595
  return result;
614
596
  }
615
- //#endregion
616
- //#region src/host/items/load.ts
597
+ // src/host/items/load.ts
617
598
  const ITEMS_DIR = "items";
618
599
  /** At most this many items in one world. */
619
600
  const MAX_ITEMS = 2e3;
@@ -641,7 +622,7 @@ async function loadItems(worldDir, context) {
641
622
  return result;
642
623
  }
643
624
  try {
644
- const own = await readDocument(join(dir, SLOTS_FILE_NAME), parseSlotsFile, result.problems);
625
+ const own = await readDocument$1(join(dir, SLOTS_FILE_NAME), parseSlotsFile, result.problems);
645
626
  for (const slot of own ?? []) {
646
627
  const at = result.slots.findIndex((existing) => existing.id === slot.id);
647
628
  if (at < 0) result.slots.push(slot);
@@ -657,7 +638,7 @@ async function loadItems(worldDir, context) {
657
638
  for (const folder of folders) {
658
639
  const file = join(dir, folder, ITEM_FILE_NAME);
659
640
  try {
660
- const item = await readDocument(file, (text) => parseItemFile(text, folder), result.problems);
641
+ const item = await readDocument$1(file, (text) => parseItemFile(text, folder), result.problems);
661
642
  if (item === void 0) continue;
662
643
  const owner = folderOf.get(item.id);
663
644
  if (owner !== void 0) {
@@ -739,8 +720,7 @@ function containersFirst(items) {
739
720
  for (const item of items) place(item);
740
721
  return ordered;
741
722
  }
742
- //#endregion
743
- //#region src/host/locations/load.ts
723
+ // src/host/locations/load.ts
744
724
  const LOCATIONS_DIR = "locations";
745
725
  /**
746
726
  * Read the places of one world: every subfolder of `<world>/locations/` that holds a
@@ -768,7 +748,7 @@ async function loadLocations(worldDir) {
768
748
  for (const folder of folders) {
769
749
  const file = join(dir, folder, LOCATION_FILE_NAME);
770
750
  try {
771
- const location = await readDocument(file, (text) => parseLocationFile(text, folder), result.problems);
751
+ const location = await readDocument$1(file, (text) => parseLocationFile(text, folder), result.problems);
772
752
  if (location === void 0) continue;
773
753
  const owner = files.get(location.id);
774
754
  if (owner !== void 0) {
@@ -841,8 +821,7 @@ function parentsFirst(locations) {
841
821
  for (const location of locations) place(location);
842
822
  return ordered;
843
823
  }
844
- //#endregion
845
- //#region src/host/lore/load.ts
824
+ // src/host/lore/load.ts
846
825
  const LORE_DIR = "lore";
847
826
  async function loadLore(worldDir) {
848
827
  const dir = join(worldDir, LORE_DIR);
@@ -864,7 +843,7 @@ async function loadLore(worldDir) {
864
843
  for (const folder of folders) {
865
844
  const file = join(dir, folder, LORE_FILE_NAME);
866
845
  try {
867
- const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
846
+ const entry = await readDocument$1(file, (text) => parseLoreFile(text, folder), result.problems);
868
847
  if (entry === void 0) continue;
869
848
  const owner = owners.get(entry.id);
870
849
  if (owner !== void 0) {
@@ -889,8 +868,7 @@ async function loadLore(worldDir) {
889
868
  });
890
869
  return result;
891
870
  }
892
- //#endregion
893
- //#region src/host/triggers/load.ts
871
+ // src/host/triggers/load.ts
894
872
  const TRIGGERS_FILE_NAME = "triggers.json";
895
873
  /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
896
874
  function parseTriggersFile(text) {
@@ -949,7 +927,7 @@ async function loadTriggers(worldDir) {
949
927
  };
950
928
  const file = join(worldDir, TRIGGERS_FILE_NAME);
951
929
  try {
952
- result.triggers = await readDocument(file, parseTriggersFile, result.problems) ?? [];
930
+ result.triggers = await readDocument$1(file, parseTriggersFile, result.problems) ?? [];
953
931
  } catch (error) {
954
932
  if (error.code !== "ENOENT") result.problems.push({
955
933
  path: file,
@@ -958,8 +936,7 @@ async function loadTriggers(worldDir) {
958
936
  }
959
937
  return result;
960
938
  }
961
- //#endregion
962
- //#region src/host/sessions/populate.ts
939
+ // src/host/sessions/populate.ts
963
940
  /** What is wrong with how the characters stand towards each other, found before anything is created. */
964
941
  function relationshipProblems(characters) {
965
942
  const ids = new Set(characters.map((character) => character.id));
@@ -1336,8 +1313,7 @@ function populateTriggers(session, definitions) {
1336
1313
  })));
1337
1314
  for (const definition of definitions) session.triggers.add(definition, "world", 0);
1338
1315
  }
1339
- //#endregion
1340
- //#region src/host/worlds/validated-world.ts
1316
+ // src/host/worlds/validated-world.ts
1341
1317
  /**
1342
1318
  * Reads everything a world's files hold and checks it all as a session start does: every file reads, and what refers to something refers to something that is there.
1343
1319
  * @throws {InvalidWorldError} naming every problem of the first part of the world that has any.
@@ -1447,10 +1423,9 @@ async function loadValidatedWorld(world) {
1447
1423
  commands: commandFile.commands
1448
1424
  };
1449
1425
  }
1450
- //#endregion
1451
- //#region src/host/worlds/world-check.ts
1426
+ // src/host/worlds/world-check.ts
1452
1427
  /** The most problems listed at once: the rest are named by their number. */
1453
- const LISTED = 40;
1428
+ const LISTED$1 = 40;
1454
1429
  /**
1455
1430
  * Whether a session could be started from the world as its files are now, and if not why, in the words a person or an assistant can act on. Starting a session runs the same
1456
1431
  * check; it names the problems of the first part of the world that has any (characters, factions, places, calendar, dice, items, lore, tracked values, triggers, plots), so
@@ -1473,13 +1448,12 @@ async function checkWorld(world) {
1473
1448
  return {
1474
1449
  ok: false,
1475
1450
  summary: error.message,
1476
- problems: problems.slice(0, LISTED),
1477
- more: Math.max(0, problems.length - LISTED)
1451
+ problems: problems.slice(0, LISTED$1),
1452
+ more: Math.max(0, problems.length - LISTED$1)
1478
1453
  };
1479
1454
  }
1480
1455
  }
1481
- //#endregion
1482
- //#region src/host/import/casting.ts
1456
+ // src/host/import/casting.ts
1483
1457
  const CASTING_SCHEMA = {
1484
1458
  type: "object",
1485
1459
  properties: {
@@ -1503,7 +1477,10 @@ const CASTING_SCHEMA = {
1503
1477
  name: { type: "string" },
1504
1478
  command: { type: "string" },
1505
1479
  happens: { type: "string" },
1506
- need: { type: "string" },
1480
+ need: {
1481
+ type: "string",
1482
+ enum: ["arrival", "introduction"]
1483
+ },
1507
1484
  text: { type: "string" },
1508
1485
  options: {
1509
1486
  type: "array",
@@ -1566,10 +1543,10 @@ function castingDocuments(answer, passages = []) {
1566
1543
  const name = str(mechanism["name"]);
1567
1544
  const command = usable.find((entry) => entry.word === str(mechanism["command"]).toLowerCase());
1568
1545
  const happens = str(mechanism["happens"]) || (command === void 0 && str(mechanism["command"]) !== "" ? str(mechanism["name"]) : "");
1569
- const need = str(mechanism["need"]);
1546
+ const need = mechanism["need"] === "introduction" ? "introduction" : "arrival";
1570
1547
  const options = Array.isArray(mechanism["options"]) ? mechanism["options"].map(str).filter((option) => option !== "") : [];
1571
- let words = str(mechanism["text"]) || need;
1572
- if (name === "" || need === "" || command === void 0 && happens === "") {
1548
+ let words = str(mechanism["text"]) || name;
1549
+ if (name === "" || command === void 0 && happens === "") {
1573
1550
  notes.push(`casting not carried: "${name || "unnamed"}" has no reason to start it`);
1574
1551
  continue;
1575
1552
  }
@@ -1643,8 +1620,90 @@ async function extractCasting(ctx, card, passages) {
1643
1620
  };
1644
1621
  }
1645
1622
  }
1646
- //#endregion
1647
- //#region src/host/lorebooks/lorebooks.ts
1623
+ // src/host/import/structure.ts
1624
+ /** The most example lines the character keeps. */
1625
+ const MAX_EXAMPLES = 8;
1626
+ /** The summary is the start of the description: a sentence or two. */
1627
+ const SUMMARY_CHARS = 280;
1628
+ /** The lines of the example messages that the character speaks, as written; the markers of the tool that wrote them are taken out. */
1629
+ function exampleLines(text, name) {
1630
+ const lines = cleanText(text, name).split("\n").map((line) => line.trim()).filter((line) => line !== "");
1631
+ const speaker = /^([^:\n]{1,100}):\s*(.*)$/;
1632
+ if (!lines.some((line) => speaker.test(line))) return lines.slice(0, MAX_EXAMPLES);
1633
+ const names = new Set([name, name.split(/\s+/)[0] ?? ""].map((part) => part.toLocaleLowerCase()));
1634
+ return lines.flatMap((line) => {
1635
+ const match = speaker.exec(line);
1636
+ if (match?.[1] === void 0 || !names.has(match[1].trim().toLocaleLowerCase())) return [];
1637
+ const utterance = match[2]?.trim();
1638
+ return utterance === void 0 || utterance === "" ? [] : [utterance];
1639
+ }).slice(0, MAX_EXAMPLES);
1640
+ }
1641
+ /**
1642
+ * What a card holds, laid out without a model: the card's own character from its description, personality and examples, its lorebook entries as lore in its own words (for the game master only,
1643
+ * as nothing has read what they say), and its instructions as the narration style, word for word. No place, faction, thing or other person is found: those take a reader.
1644
+ */
1645
+ function structureOnly(card, items, _choices) {
1646
+ const taken = /* @__PURE__ */ new Set();
1647
+ const roster = [{
1648
+ kind: "character",
1649
+ key: uniqueKey(slug(card.name, "character"), taken),
1650
+ name: card.name,
1651
+ aliases: [],
1652
+ player: false
1653
+ }];
1654
+ const target = [{
1655
+ name: card.name,
1656
+ kind: "character"
1657
+ }];
1658
+ const classified = {};
1659
+ for (const item of items) if (item.id.startsWith("field:description") || item.id.startsWith("field:personality")) classified[item.id] = {
1660
+ roles: ["character"],
1661
+ targets: target
1662
+ };
1663
+ else if (item.id.startsWith("field:example")) classified[item.id] = {
1664
+ roles: ["speech"],
1665
+ targets: target
1666
+ };
1667
+ else if (item.id.startsWith("field:")) classified[item.id] = {
1668
+ roles: ["scenario"],
1669
+ targets: []
1670
+ };
1671
+ else classified[item.id] = {
1672
+ roles: ["world"],
1673
+ targets: []
1674
+ };
1675
+ const extracted = emptyExtracted();
1676
+ const description = cleanText(card.description, card.name);
1677
+ const built = characterDocument(roster[0], {
1678
+ tier: "principal",
1679
+ kind: "person",
1680
+ summary: description.slice(0, SUMMARY_CHARS).trim(),
1681
+ personality: cleanText(card.personality, card.name),
1682
+ background: description,
1683
+ speech: {
1684
+ style: "",
1685
+ examples: exampleLines(card.messageExample, card.name)
1686
+ }
1687
+ }, roster);
1688
+ extracted.characters.push(built.document);
1689
+ extracted.notes.push(...built.notes);
1690
+ for (const item of items.filter((entry) => entry.id.startsWith("entry:"))) for (const entry of loreDocuments(asWritten(item), roster, taken)) addLore(extracted.lore, {
1691
+ ...entry.document,
1692
+ scope: "listed"
1693
+ });
1694
+ const instructions = [card.systemPrompt, card.postHistoryInstructions].map((text) => cleanText(text, card.name)).filter((text) => text !== "");
1695
+ if (instructions.length > 0) extracted.prompts.push({
1696
+ id: "roleplay/style",
1697
+ text: inert(instructions.join("\n\n"))
1698
+ });
1699
+ extracted.notes.push("imported without a model: only the card's own character, its lorebook and its instructions were carried over");
1700
+ return {
1701
+ classified,
1702
+ roster,
1703
+ extracted
1704
+ };
1705
+ }
1706
+ // src/host/lorebooks/lorebooks.ts
1648
1707
  const LOREBOOKS_FOLDER = "lorebooks";
1649
1708
  const LOREBOOK_FILE = "lorebook.json";
1650
1709
  const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
@@ -1926,8 +1985,7 @@ function parseWorldInfoEdit(value) {
1926
1985
  if (problems.length > 0) throw new InvalidEditProblems(problems);
1927
1986
  return edit;
1928
1987
  }
1929
- //#endregion
1930
- //#region src/host/worlds/world-file.ts
1988
+ // src/host/worlds/world-file.ts
1931
1989
  const WORLD_FILE_NAME = "world.json";
1932
1990
  /** `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. */
1933
1991
  function readAlternateOpenings(reader) {
@@ -2098,8 +2156,7 @@ function parseWorldFile(text) {
2098
2156
  }
2099
2157
  };
2100
2158
  }
2101
- //#endregion
2102
- //#region src/host/worlds/world-file-io.ts
2159
+ // src/host/worlds/world-file-io.ts
2103
2160
  const queues = /* @__PURE__ */ new Map();
2104
2161
  /**
2105
2162
  * Runs `work` after everything asked for the same folder before it has finished. The import, the editor and the assistant each read `world.json`, change a field and write it
@@ -2125,13 +2182,9 @@ function updateWorldFile(directory, update) {
2125
2182
  return document;
2126
2183
  });
2127
2184
  }
2128
- //#endregion
2129
- //#region src/host/import/finish.ts
2130
- const STAGE = "stage";
2131
- const MAX_DESCRIPTION = 500;
2132
- const MAX_TAGS = 8;
2133
- const MAX_TAG = 30;
2134
- const FOLDERS = [
2185
+ // src/host/worlds/entity-folders.ts
2186
+ /** The five kinds of entity a world is made of: where each lives (`<directory>/<id>/<file>`) and the key of its group in the importer's output. */
2187
+ const ENTITY_FOLDERS = [
2135
2188
  {
2136
2189
  key: "characters",
2137
2190
  directory: CHARACTERS_DIR,
@@ -2158,6 +2211,11 @@ const FOLDERS = [
2158
2211
  file: LORE_FILE_NAME
2159
2212
  }
2160
2213
  ];
2214
+ // src/host/import/finish.ts
2215
+ const STAGE = "stage";
2216
+ const MAX_DESCRIPTION = 500;
2217
+ const MAX_TAGS = 8;
2218
+ const MAX_TAG = 30;
2161
2219
  /** The card's other greetings, as the other openings a player may start with: the first message and the alternates that were not chosen. */
2162
2220
  function alternateOpenings(card, chosen, player) {
2163
2221
  if (chosen.kind === "none") return [];
@@ -2325,6 +2383,10 @@ function worldJob(text, tr, card, roster, scenario, opening) {
2325
2383
  /** The description and tags of the world: asked of one call, and from the card's own fields when that fails. */
2326
2384
  async function describeWorld(ctx, card, roster, items, opening) {
2327
2385
  const scenario = items.filter((item) => item.id.startsWith("field:scenario")).map((item) => item.text).join("\n\n");
2386
+ if (ctx.noModel === true) return {
2387
+ description: (scenario || cleanText(card.description, card.name)).slice(0, MAX_DESCRIPTION).trim(),
2388
+ tags: card.tags.filter((tag) => tag.trim() !== "" && tag.length <= MAX_TAG).slice(0, MAX_TAGS)
2389
+ };
2328
2390
  try {
2329
2391
  const answer = await ctx.run(worldJob(ctx.text, trOf(ctx), card, roster, scenario, opening));
2330
2392
  return {
@@ -2341,7 +2403,7 @@ async function describeWorld(ctx, card, roster, items, opening) {
2341
2403
  }
2342
2404
  }
2343
2405
  async function hasEntities(world) {
2344
- for (const { directory } of FOLDERS) try {
2406
+ for (const { directory } of ENTITY_FOLDERS) try {
2345
2407
  if ((await readdir(join(world, directory))).some((name) => !name.startsWith("."))) return true;
2346
2408
  } catch (error) {
2347
2409
  if (error.code !== "ENOENT") throw error;
@@ -2398,7 +2460,7 @@ async function finishImport(ctx, input) {
2398
2460
  if (extracted.variables.length > 0) await writeAtomically(join(stage, VARIABLES_FILE_NAME), `${JSON.stringify(extracted.variables, null, 2)}\n`);
2399
2461
  if (extracted.commands.length > 0) await writeAtomically(join(stage, COMMANDS_FILE_NAME), `${JSON.stringify({ commands: extracted.commands }, null, 2)}\n`);
2400
2462
  if (extracted.triggers.length > 0) await writeAtomically(join(stage, TRIGGERS_FILE_NAME), `${JSON.stringify(extracted.triggers, null, 2)}\n`);
2401
- for (const { key, directory: folder, file } of FOLDERS) for (const document of extracted[key]) await writeAtomically(join(stage, folder, String(document["id"]), file), `${JSON.stringify(document, null, 2)}\n`);
2463
+ for (const { key, directory: folder, file } of ENTITY_FOLDERS) for (const document of extracted[key]) await writeAtomically(join(stage, folder, String(document["id"]), file), `${JSON.stringify(document, null, 2)}\n`);
2402
2464
  for (const { id, text } of extracted.prompts) {
2403
2465
  const problem = promptProblem("en", id, text);
2404
2466
  if (problem !== void 0) return {
@@ -2409,7 +2471,7 @@ async function finishImport(ctx, input) {
2409
2471
  if (extracted.variables.length > 0) await rename(join(stage, VARIABLES_FILE_NAME), join(directory, VARIABLES_FILE_NAME));
2410
2472
  if (extracted.commands.length > 0) await rename(join(stage, COMMANDS_FILE_NAME), join(directory, COMMANDS_FILE_NAME));
2411
2473
  if (extracted.triggers.length > 0) await rename(join(stage, TRIGGERS_FILE_NAME), join(directory, TRIGGERS_FILE_NAME));
2412
- for (const { directory: folder } of FOLDERS) {
2474
+ for (const { directory: folder } of ENTITY_FOLDERS) {
2413
2475
  const from = join(stage, folder);
2414
2476
  if (await stat(from).then(() => true, () => false)) await rename(from, join(directory, folder));
2415
2477
  }
@@ -2496,8 +2558,7 @@ async function finishImport(ctx, input) {
2496
2558
  ...check.ok ? {} : { draft: check }
2497
2559
  };
2498
2560
  }
2499
- //#endregion
2500
- //#region src/host/import/pictures.ts
2561
+ // src/host/import/pictures.ts
2501
2562
  /** The address is not one a picture may be fetched from: it names this machine or a private network. */
2502
2563
  var BlockedAddressError = class extends Error {};
2503
2564
  const MAX_BYTES = 20971520;
@@ -2869,8 +2930,7 @@ function mergeReports(earlier, later, found) {
2869
2930
  skipped: [...(earlier?.skipped ?? []).filter((entry) => !asked.has(addressKey(entry.url))), ...later.skipped]
2870
2931
  };
2871
2932
  }
2872
- //#endregion
2873
- //#region src/host/catalogue/errors.ts
2933
+ // src/host/catalogue/errors.ts
2874
2934
  var CatalogueError = class extends Error {
2875
2935
  failure;
2876
2936
  detail;
@@ -2880,8 +2940,7 @@ var CatalogueError = class extends Error {
2880
2940
  this.detail = detail;
2881
2941
  }
2882
2942
  };
2883
- //#endregion
2884
- //#region src/host/catalogue/origin.ts
2943
+ // src/host/catalogue/origin.ts
2885
2944
  const ORIGIN_FILE = ".catalogue.json";
2886
2945
  const MAX_LISTED_CHANGES = 12;
2887
2946
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -2962,8 +3021,7 @@ async function localChanges(directory) {
2962
3021
  if (origin?.kind !== "release") return "unverified";
2963
3022
  return compare(origin.files, await hashWorld(directory));
2964
3023
  }
2965
- //#endregion
2966
- //#region src/host/import/snapshot.ts
3024
+ // src/host/import/snapshot.ts
2967
3025
  const SNAPSHOT = "files.json";
2968
3026
  /** The pictures of a world are fetched and generated in the background and are not what a card says. */
2969
3027
  const notTheCards = (path) => path.startsWith("images/");
@@ -2987,21 +3045,20 @@ async function editsSince(directory) {
2987
3045
  changes: describeChanges(changes)
2988
3046
  };
2989
3047
  }
2990
- //#endregion
2991
- //#region src/host/import/provenance.ts
2992
- const FILE = "provenance.json";
3048
+ // src/host/import/provenance.ts
3049
+ const FILE$1 = "provenance.json";
2993
3050
  const PROVENANCE_SCHEMA = "dsh-roleplay-import/v1";
2994
3051
  /** The import record of a world, or nothing for a world imported before records were kept. */
2995
3052
  async function readProvenance(directory) {
2996
3053
  let text;
2997
3054
  try {
2998
- text = await readFile(join(directory, IMPORT_FOLDER, FILE), "utf8");
3055
+ text = await readFile(join(directory, IMPORT_FOLDER, FILE$1), "utf8");
2999
3056
  } catch (error) {
3000
3057
  if (error.code === "ENOENT") return void 0;
3001
3058
  throw error;
3002
3059
  }
3003
3060
  const value = JSON.parse(text);
3004
- if (value.schema !== "dsh-roleplay-import/v1" || !Array.isArray(value.history)) throw new Error(`${FILE} is not an import record this version reads`);
3061
+ if (value.schema !== "dsh-roleplay-import/v1" || !Array.isArray(value.history)) throw new Error(`${FILE$1} is not an import record this version reads`);
3005
3062
  return value;
3006
3063
  }
3007
3064
  /** Adds one line to the world's import record: what card it came from and, for an import, what was written. */
@@ -3015,13 +3072,1860 @@ async function recordProvenance(directory, entry, cardJson) {
3015
3072
  sha256: createHash("sha256").update(cardJson).digest("hex")
3016
3073
  }
3017
3074
  };
3018
- await atomicWriteJson(join(directory, IMPORT_FOLDER, FILE), {
3075
+ await atomicWriteJson(join(directory, IMPORT_FOLDER, FILE$1), {
3019
3076
  schema: PROVENANCE_SCHEMA,
3020
3077
  history: [...earlier?.history ?? [], line]
3021
3078
  });
3022
3079
  }
3023
- //#endregion
3024
- //#region src/host/import/run-import.ts
3080
+ // src/shared/checks.ts
3081
+ /** A check suite is made of kits; a person asks for kits with a command and an assistant with a tool. */
3082
+ const KITS = [
3083
+ "consistency",
3084
+ "fidelity",
3085
+ "quality"
3086
+ ];
3087
+ const SEVERITIES = [
3088
+ "error",
3089
+ "warning",
3090
+ "info"
3091
+ ];
3092
+ /** The commands of an authoring chat that start checks, and the kits each runs. */
3093
+ const CHECK_COMMANDS = {
3094
+ check: [
3095
+ "consistency",
3096
+ "fidelity",
3097
+ "quality"
3098
+ ],
3099
+ "check-all": [
3100
+ "consistency",
3101
+ "fidelity",
3102
+ "quality"
3103
+ ],
3104
+ "check-world": ["consistency"],
3105
+ "check-card": ["fidelity"],
3106
+ "check-quality": ["quality"]
3107
+ };
3108
+ const findingKey = (finding) => `${finding.check}\n${finding.code}\n${finding.where}\n${finding.message}`;
3109
+ // src/host/import/card-tools.ts
3110
+ /** The most of a piece one `card_read` returns; a long lorebook entry is read in turns. */
3111
+ const READ_CHARS = 6e3;
3112
+ const SNIPPET_CHARS = 240;
3113
+ const DEFAULT_HITS = 8;
3114
+ const MAX_HITS = 20;
3115
+ const baseId = (id) => id.replace(/#\d+$/, "");
3116
+ /** The folder inside `.import` where a newer version of the card waits to be applied to the world. */
3117
+ const UPDATE_FOLDER = "update";
3118
+ /** Everything the card holds, in the order the card has it. */
3119
+ function cardPieces(card, choices) {
3120
+ const read = new Set(itemise(card, choices).map((item) => baseId(item.id)));
3121
+ const field = (id, label, text) => text.trim() === "" ? [] : [{
3122
+ id,
3123
+ label,
3124
+ title: "",
3125
+ keys: [],
3126
+ text,
3127
+ used: read.has(id)
3128
+ }];
3129
+ return [
3130
+ ...field("field:description", "description", card.description),
3131
+ ...field("field:personality", "personality", card.personality),
3132
+ ...field("field:scenario", "scenario", card.scenario),
3133
+ ...field("field:example", "example messages", card.messageExample),
3134
+ ...field("field:first-message", "first message", card.firstMessage),
3135
+ ...card.alternateGreetings.flatMap((text, index) => field(`field:greeting-${index + 1}`, `alternate greeting ${index + 1}`, text)),
3136
+ ...field("field:creator-notes", "creator's notes", card.creatorNotes),
3137
+ ...field("field:system-prompt", "system prompt", card.systemPrompt),
3138
+ ...field("field:post-history", "post-history instructions", card.postHistoryInstructions),
3139
+ ...(card.book?.entries ?? []).filter((entry) => entry.content.trim() !== "").map((entry) => ({
3140
+ id: entry.id,
3141
+ label: entry.title === "" ? entry.id : `entry “${entry.title}”`,
3142
+ title: entry.title,
3143
+ keys: entry.keys,
3144
+ text: entry.content,
3145
+ used: read.has(entry.id),
3146
+ enabled: entry.enabled
3147
+ }))
3148
+ ];
3149
+ }
3150
+ async function optional(file) {
3151
+ try {
3152
+ return JSON.parse(await readFile(file, "utf8"));
3153
+ } catch (error) {
3154
+ if (error.code === "ENOENT") return void 0;
3155
+ throw error;
3156
+ }
3157
+ }
3158
+ /** The card kept in a world's import folder, and what the import made of it. The tools exist as long as the card does. */
3159
+ async function readSource(directory, withRecords, version = "current") {
3160
+ const folder = join(directory, IMPORT_FOLDER);
3161
+ let read;
3162
+ try {
3163
+ read = await readImportFolder(version === "new" ? join(folder, UPDATE_FOLDER) : folder);
3164
+ } catch (error) {
3165
+ if (error.code === "ENOENT") throw new Error(version === "new" ? "no newer version of the card is waiting to update this world" : "this world has no source card: it was not imported from one, or its .import folder was removed");
3166
+ throw error;
3167
+ }
3168
+ const records = withRecords && version === "current" ? {
3169
+ classified: await optional(join(folder, "classification.json")),
3170
+ roster: await optional(join(folder, "roster.json")),
3171
+ report: await optional(join(folder, "report.json"))
3172
+ } : {};
3173
+ return {
3174
+ card: read.card,
3175
+ choices: read.choices,
3176
+ pieces: cardPieces(read.card, read.choices),
3177
+ records
3178
+ };
3179
+ }
3180
+ const rolesOf = (classified, id) => {
3181
+ if (classified === void 0) return [];
3182
+ return [...new Set(Object.entries(classified).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
3183
+ };
3184
+ function snippet$1(text, at, length) {
3185
+ const start = Math.max(0, at - Math.floor((SNIPPET_CHARS - length) / 2));
3186
+ const end = Math.min(text.length, start + SNIPPET_CHARS);
3187
+ return `${start > 0 ? "…" : ""}${text.slice(start, end).replace(/\s+/g, " ")}${end < text.length ? "…" : ""}`;
3188
+ }
3189
+ function searchPieces(pieces, query, limit) {
3190
+ const phrase = query.trim().toLowerCase();
3191
+ if (phrase === "") return [];
3192
+ const words = [...new Set(phrase.split(/[\s,;,、]+/).filter((word) => word.length >= (/^[\x00-\x7f]+$/.test(word) ? 3 : 2)))];
3193
+ const count = (text, needle) => {
3194
+ let n = 0;
3195
+ let first = -1;
3196
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
3197
+ n += 1;
3198
+ if (first < 0) first = at;
3199
+ }
3200
+ return {
3201
+ n,
3202
+ first
3203
+ };
3204
+ };
3205
+ const look = (text) => {
3206
+ const lowered = text.toLowerCase();
3207
+ const whole = count(lowered, phrase);
3208
+ if (whole.n > 0) return {
3209
+ matches: whole.n,
3210
+ score: whole.n * 4 + 100,
3211
+ at: whole.first,
3212
+ length: phrase.length
3213
+ };
3214
+ const found = words.map((word) => ({
3215
+ word,
3216
+ ...count(lowered, word)
3217
+ })).filter((entry) => entry.n > 0);
3218
+ if (found.length === 0) return void 0;
3219
+ const best = found.reduce((a, b) => a.first <= b.first ? a : b, found[0]);
3220
+ return {
3221
+ matches: found.reduce((sum, entry) => sum + entry.n, 0),
3222
+ score: found.length * 10 + found.reduce((sum, entry) => sum + entry.n, 0),
3223
+ at: best.first,
3224
+ length: best.word.length
3225
+ };
3226
+ };
3227
+ return pieces.flatMap((piece) => {
3228
+ const inText = look(piece.text);
3229
+ if (inText !== void 0) return [{
3230
+ piece,
3231
+ in: "text",
3232
+ matches: inText.matches,
3233
+ score: inText.score,
3234
+ snippet: snippet$1(piece.text, inText.at, inText.length)
3235
+ }];
3236
+ const head = [piece.title, ...piece.keys].filter((part) => part !== "").join(" · ");
3237
+ const inHead = look(head);
3238
+ return inHead === void 0 ? [] : [{
3239
+ piece,
3240
+ in: "title or keys",
3241
+ matches: inHead.matches,
3242
+ score: inHead.score - 50,
3243
+ snippet: `${piece.title === "" ? "" : `title: ${piece.title}`}${piece.keys.length === 0 ? "" : `${piece.title === "" ? "" : "; "}keys: ${piece.keys.join(", ")}`}`
3244
+ }];
3245
+ }).sort((a, b) => b.score - a.score).slice(0, limit).map(({ piece, matches, in: where, snippet: text }) => ({
3246
+ piece,
3247
+ matches,
3248
+ in: where,
3249
+ snippet: text
3250
+ }));
3251
+ }
3252
+ const versionParameter = {
3253
+ type: "string",
3254
+ enum: ["current", "new"],
3255
+ description: "current (the default) is the card the world was made from; new is the newer version waiting to update it, when card_diff says there is one. Piece ids are those of that version."
3256
+ };
3257
+ const output$1 = {
3258
+ schema: { type: "json" },
3259
+ render: (_args, value) => [{
3260
+ type: "text",
3261
+ text: JSON.stringify(value, null, 1)
3262
+ }]
3263
+ };
3264
+ const json$1 = (value) => JSON.parse(JSON.stringify(value));
3265
+ const idOf = (exec) => {
3266
+ const chat = exec.agent?.session.id;
3267
+ const world = chat === void 0 ? void 0 : authoredWorldOf(chat);
3268
+ if (world === void 0) throw new Error("this tool is available only in a world authoring chat");
3269
+ return world;
3270
+ };
3271
+ /**
3272
+ * Read-only tools over the card a world was imported from, which stays in the world's `.import` folder: they work while that folder holds the card and say so when it does not.
3273
+ * `records` adds what the import made of the card (the role of each piece, who it was used for); it is off only when a test compares the agent with and without it.
3274
+ */
3275
+ function cardTools(worlds, options = {}) {
3276
+ const withRecords = options.records !== false;
3277
+ const source = async (exec, version = "current") => {
3278
+ const id = idOf(exec);
3279
+ const record = await worlds.find(id);
3280
+ if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
3281
+ return await readSource(record.directory, withRecords, version);
3282
+ };
3283
+ const versionOf = (value) => {
3284
+ if (value === void 0 || value === "current") return "current";
3285
+ if (value === "new") return "new";
3286
+ throw new Error("version must be current or new");
3287
+ };
3288
+ const find = (pieces, id) => {
3289
+ const found = pieces.find((piece) => piece.id === id);
3290
+ if (found === void 0) throw new Error(`the card has no piece "${id}": use an id from card_overview or card_search`);
3291
+ return found;
3292
+ };
3293
+ return [
3294
+ defineTool({
3295
+ name: "card_overview",
3296
+ description: "The card this world was imported from, which is kept: its name, creator and tags, every piece of it (field, greeting or lorebook entry) with its size, and, from the import's own records, what each piece was taken to be and which characters, places and things were made from it. Start here when the person asks where something in the world came from.",
3297
+ parameters: {},
3298
+ output: output$1,
3299
+ isConcurrencySafe: () => true,
3300
+ async execute(_args, exec) {
3301
+ const { card, choices, pieces, records } = await source(exec);
3302
+ const madeFrom = entitiesByPiece({
3303
+ card,
3304
+ choices,
3305
+ pieces,
3306
+ records
3307
+ });
3308
+ const made = (id) => madeFrom.get(id) ?? [];
3309
+ return json$1({
3310
+ card: {
3311
+ name: card.name,
3312
+ creator: card.creator,
3313
+ version: card.characterVersion,
3314
+ tags: card.tags,
3315
+ format: card.sourceSpec,
3316
+ ignoredScripts: card.ignored.scripts
3317
+ },
3318
+ pieces: pieces.map((piece) => ({
3319
+ id: piece.id,
3320
+ label: piece.label,
3321
+ characters: piece.text.length,
3322
+ readByTheImport: piece.used,
3323
+ ...piece.enabled === void 0 ? {} : { switchedOnInCard: piece.enabled },
3324
+ ...withRecords ? {
3325
+ takenToBe: rolesOf(records.classified, piece.id),
3326
+ madeInto: made(piece.id)
3327
+ } : {}
3328
+ })),
3329
+ ...records.roster === void 0 ? {} : { imported: records.roster.map((entity) => ({
3330
+ name: entity.name,
3331
+ kind: entity.kind,
3332
+ aliases: entity.aliases,
3333
+ playedByThePlayer: entity.player
3334
+ })) },
3335
+ ...records.report === void 0 ? {} : {
3336
+ importNotes: records.report.notes,
3337
+ leftOut: records.report.leftOut
3338
+ },
3339
+ note: "The import's records are its own judgement and can be wrong or incomplete; check them against the text of the piece with card_read."
3340
+ });
3341
+ }
3342
+ }),
3343
+ defineTool({
3344
+ name: "card_search",
3345
+ description: "Searches everything the card says (fields, greetings, lorebook entries and their keys) for a name or phrase and returns the pieces that contain it, best first, each with a short snippet and whether it was found in the text or only in the title or keys of an entry. A hit is a pointer, not evidence: read the piece with card_read before you answer from it.",
3346
+ parameters: {
3347
+ query: {
3348
+ type: "string",
3349
+ required: true,
3350
+ description: "A name or phrase to look for, in the card's own language."
3351
+ },
3352
+ version: versionParameter,
3353
+ limit: {
3354
+ type: "number",
3355
+ description: `How many pieces to return, at most ${MAX_HITS} (default ${DEFAULT_HITS}).`
3356
+ }
3357
+ },
3358
+ output: output$1,
3359
+ isConcurrencySafe: () => true,
3360
+ async execute(args, exec) {
3361
+ const { pieces } = await source(exec, versionOf(args.version));
3362
+ const limit = Math.min(MAX_HITS, Math.max(1, Math.floor(typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : DEFAULT_HITS)));
3363
+ const hits = searchPieces(pieces, args.query, limit);
3364
+ return json$1({
3365
+ query: args.query,
3366
+ found: hits.length,
3367
+ hits: hits.map(({ piece, matches, in: where, snippet: text }) => ({
3368
+ piece: piece.id,
3369
+ label: piece.label,
3370
+ matches,
3371
+ foundIn: where,
3372
+ snippet: text
3373
+ }))
3374
+ });
3375
+ }
3376
+ }),
3377
+ defineTool({
3378
+ name: "card_read",
3379
+ description: `The text of one piece of the card, word for word as the card has it (the card's own placeholders such as {{user}} included). A long piece is read in turns of ${READ_CHARS} characters: when "next" is given, call again with that offset.`,
3380
+ parameters: {
3381
+ piece: {
3382
+ type: "string",
3383
+ required: true,
3384
+ description: "A piece id from card_overview, card_search or card_diff, such as field:description or entry:3."
3385
+ },
3386
+ version: versionParameter,
3387
+ offset: {
3388
+ type: "number",
3389
+ description: "Where to start reading, in characters (default 0)."
3390
+ }
3391
+ },
3392
+ output: output$1,
3393
+ isConcurrencySafe: () => true,
3394
+ async execute(args, exec) {
3395
+ const { pieces } = await source(exec, versionOf(args.version));
3396
+ const piece = find(pieces, args.piece);
3397
+ const from = Math.min(piece.text.length, Math.max(0, Math.floor(typeof args.offset === "number" && Number.isFinite(args.offset) ? args.offset : 0)));
3398
+ const to = Math.min(piece.text.length, from + READ_CHARS);
3399
+ return json$1({
3400
+ piece: piece.id,
3401
+ label: piece.label,
3402
+ ...piece.keys.length === 0 ? {} : { keys: piece.keys },
3403
+ from,
3404
+ to,
3405
+ of: piece.text.length,
3406
+ ...to < piece.text.length ? { next: to } : {},
3407
+ text: piece.text.slice(from, to)
3408
+ });
3409
+ }
3410
+ }),
3411
+ defineTool({
3412
+ name: "card_origin",
3413
+ description: "Where a character, place, organisation or thing of this world came from: the pieces of the card the import read to make it (the pieces about it first, then those that only mention it), with what each was taken to be. For a name the import did not make anything of, the pieces of the card that mention it. Then read the pieces with card_read to answer from their text.",
3414
+ parameters: { name: {
3415
+ type: "string",
3416
+ required: true,
3417
+ description: "The name or an alias, as the world or the card has it."
3418
+ } },
3419
+ output: output$1,
3420
+ isConcurrencySafe: () => true,
3421
+ async execute(args, exec) {
3422
+ const { card, choices, pieces, records } = await source(exec);
3423
+ const entity = records.roster === void 0 ? void 0 : findEntity(records.roster, args.name);
3424
+ if (entity === void 0 || records.classified === void 0) return json$1({
3425
+ name: args.name,
3426
+ madeByTheImport: false,
3427
+ mentions: searchPieces(pieces, args.name, DEFAULT_HITS).map(({ piece, in: where, snippet: text }) => ({
3428
+ piece: piece.id,
3429
+ label: piece.label,
3430
+ foundIn: where,
3431
+ snippet: text
3432
+ }))
3433
+ });
3434
+ return json$1({
3435
+ name: entity.name,
3436
+ kind: entity.kind,
3437
+ aliases: entity.aliases,
3438
+ madeByTheImport: true,
3439
+ usedPieces: originOf(card, choices, pieces, records, entity.name).map((entry) => ({
3440
+ piece: entry.piece,
3441
+ label: entry.label,
3442
+ how: entry.how,
3443
+ takenToBe: rolesOf(records.classified, entry.piece)
3444
+ }))
3445
+ });
3446
+ }
3447
+ })
3448
+ ];
3449
+ }
3450
+ /** For each piece of the card, the names of the characters, places and things the import made from it. */
3451
+ function entitiesByPiece(source) {
3452
+ const made = /* @__PURE__ */ new Map();
3453
+ for (const entity of source.records.roster ?? []) for (const entry of originOf(source.card, source.choices, source.pieces, source.records, entity.name)) made.set(entry.piece, [...made.get(entry.piece) ?? [], entity.name]);
3454
+ return made;
3455
+ }
3456
+ /** The pieces an entity was made from, as the build chose them: the ones the survey said are about it, then those that name it. */
3457
+ function originOf(card, choices, pieces, records, name) {
3458
+ if (records.roster === void 0 || records.classified === void 0) return [];
3459
+ const entity = findEntity(records.roster, name);
3460
+ if (entity === void 0) return [];
3461
+ const names = [entity.name, ...entity.aliases].map(norm);
3462
+ const items = itemise(card, choices);
3463
+ const chosen = sourcesFor(entity, items, records.classified);
3464
+ const about = (id) => (records.classified?.[id]?.targets ?? []).some((target) => target.kind === entity.kind && names.includes(norm(target.name)));
3465
+ const seen = /* @__PURE__ */ new Set();
3466
+ return chosen.flatMap((item) => {
3467
+ const id = baseId(item.id);
3468
+ const piece = pieces.find((entry) => entry.id === id);
3469
+ if (piece === void 0 || seen.has(id)) return [];
3470
+ seen.add(id);
3471
+ return [{
3472
+ piece: id,
3473
+ label: piece.label,
3474
+ how: about(item.id) ? "about it" : "mentions it"
3475
+ }];
3476
+ });
3477
+ }
3478
+ // src/host/checks/terms.ts
3479
+ const HAN = /[㐀-鿿]+/gu;
3480
+ /** Words of fewer letters are mostly the glue of a language, which says nothing about whether two texts share facts. */
3481
+ const MIN_LETTERS = 4;
3482
+ /** The comparable terms of a text: Latin words of four letters or more, other scripts' words of two, and the pairs of neighbouring Han characters (Chinese has no spaces). */
3483
+ function termsOf(text) {
3484
+ const found = /* @__PURE__ */ new Set();
3485
+ const lower = text.normalize("NFKC").toLowerCase();
3486
+ for (const [run] of lower.matchAll(HAN)) {
3487
+ if (run.length === 1) found.add(run);
3488
+ for (let at = 0; at + 1 < run.length; at++) found.add(run.slice(at, at + 2));
3489
+ }
3490
+ for (const [word] of lower.replace(HAN, " ").matchAll(/[\p{L}\p{N}]+/gu)) if (/^[a-z0-9]+$/u.test(word) ? word.length >= MIN_LETTERS : word.length >= 2) found.add(word);
3491
+ return found;
3492
+ }
3493
+ /** How much of `of` is found in `within`, from 0 to 1; a text with no terms counts as found. */
3494
+ function shareOf(of, within) {
3495
+ if (of.size === 0) return 1;
3496
+ let shared = 0;
3497
+ for (const term of of) if (within.has(term)) shared += 1;
3498
+ return shared / of.size;
3499
+ }
3500
+ /** A text as names are looked up in it: width- and case-folded. */
3501
+ const folded = (text) => text.normalize("NFKC").toLowerCase();
3502
+ // src/host/checks/card-evidence.ts
3503
+ const exists = async (file) => await stat(file).then(() => true, () => false);
3504
+ /** @returns the card of the world, or nothing when the world has none (or no newer version waits, for `new`). */
3505
+ async function loadCardEvidence(directory, version) {
3506
+ const folder = join(directory, IMPORT_FOLDER);
3507
+ if (!await exists(join(folder, "card.json"))) return void 0;
3508
+ if (version === "current") return {
3509
+ version,
3510
+ source: await readSource(directory, true)
3511
+ };
3512
+ if (!await exists(join(folder, "update", "card.json"))) return void 0;
3513
+ return {
3514
+ version,
3515
+ source: await readSource(directory, false, "new"),
3516
+ previous: await readSource(directory, true)
3517
+ };
3518
+ }
3519
+ /** A lore entry or the world's own file counts as made from a piece when this much of its terms are in the piece: a rewrite keeps the facts, and so the words. */
3520
+ const MADE_FROM = .6;
3521
+ const MIN_TERMS = 4;
3522
+ /** The pieces the import read for the world: not the instructions, templates and entries left out, not those it could not classify. */
3523
+ function usedPieces(source) {
3524
+ return source.pieces.filter((piece) => {
3525
+ if (!piece.used || piece.enabled === false) return false;
3526
+ const roles = rolesOf(source.records.classified, piece.id);
3527
+ return roles.length > 0 && !isLeftOut({ roles });
3528
+ });
3529
+ }
3530
+ /**
3531
+ * Which parts of the world each piece of the card was made into: the characters, places, organisations and things the import's records say it was read for, and the lore
3532
+ * and world file whose words are mostly the piece's (lore records no source of its own). Keyed by piece, values are keys of `WorldText.texts`. With `about`, a piece that only
3533
+ * mentions an entity does not count as one it was made from: what it says of others is not that entity's.
3534
+ */
3535
+ function madeInto(source, world, only = "any") {
3536
+ const made = /* @__PURE__ */ new Map();
3537
+ const add = (piece, where) => {
3538
+ const list = made.get(piece) ?? [];
3539
+ if (!list.includes(where)) made.set(piece, [...list, where]);
3540
+ };
3541
+ const group = {
3542
+ character: "characters",
3543
+ place: "locations",
3544
+ faction: "factions",
3545
+ thing: "items"
3546
+ };
3547
+ for (const entity of source.records.roster ?? []) {
3548
+ const where = `${group[entity.kind]}/${entity.key}`;
3549
+ if (!world.texts.has(where)) continue;
3550
+ for (const entry of originOf(source.card, source.choices, source.pieces, source.records, entity.name)) if (only === "any" || entry.how === "about it") add(entry.piece, where);
3551
+ }
3552
+ const pieces = usedPieces(source).map((piece) => ({
3553
+ id: baseId(piece.id),
3554
+ terms: termsOf(piece.text)
3555
+ }));
3556
+ for (const [where, text] of world.texts) {
3557
+ if (!where.startsWith(`${ENTITY_FOLDERS[4].directory}/`) && !where.startsWith(`world.json#`)) continue;
3558
+ const terms = termsOf(text);
3559
+ if (terms.size < MIN_TERMS) continue;
3560
+ for (const piece of pieces) if (shareOf(terms, piece.terms) >= MADE_FROM) add(piece.id, where);
3561
+ }
3562
+ return made;
3563
+ }
3564
+ // src/host/checks/check.ts
3565
+ /** Thrown by a check that cannot run on this world; the report says why instead of counting it as clean. */
3566
+ var CheckSkipped = class extends Error {};
3567
+ /** A check's findings with the check's id on each. */
3568
+ const foundBy = (check, found) => found.map((finding) => ({
3569
+ ...finding,
3570
+ check
3571
+ }));
3572
+ // src/host/triggers/parts.ts
3573
+ /** 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. */
3574
+ async function loadWorldParts(directory) {
3575
+ const { characters, problems: characterProblems } = await loadCharacters(directory);
3576
+ const { locations, problems: locationProblems } = await loadLocations(directory);
3577
+ const { items, slots, problems: itemProblems } = await loadItems(directory, {
3578
+ characters: characters.map((character) => character.id),
3579
+ locations
3580
+ });
3581
+ const { defs, problems: variableProblems } = await loadVariables(directory);
3582
+ const { calendar, problems: calendarProblems } = await loadCalendar(directory);
3583
+ const problems = [
3584
+ ...characterProblems,
3585
+ ...locationProblems,
3586
+ ...itemProblems,
3587
+ ...variableProblems,
3588
+ ...calendarProblems
3589
+ ];
3590
+ if (problems.length > 0) throw new InvalidEditProblems([`the world's other files have problems that come first: ${problems.map((problem) => `${problem.path}: ${problem.message}`).join("; ")}`]);
3591
+ return {
3592
+ characters,
3593
+ locations,
3594
+ items,
3595
+ slots,
3596
+ variables: defs,
3597
+ calendar
3598
+ };
3599
+ }
3600
+ // src/host/worlds/scratch.ts
3601
+ /**
3602
+ * Runs `use` against an in-memory story made from the world's files, the way a session start fills one, and closes it again. The populate functions only use the repositories
3603
+ * a store has; the search a session adds is not needed.
3604
+ */
3605
+ function withScratchStory(parts, use) {
3606
+ const scratch = createSessionStore(":memory:", {
3607
+ id: "scratch",
3608
+ name: "scratch",
3609
+ world: {
3610
+ id: "scratch",
3611
+ name: "scratch"
3612
+ }
3613
+ }, { vectors: false });
3614
+ try {
3615
+ const session = scratch;
3616
+ if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
3617
+ populateLocations(session, parts.locations);
3618
+ populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
3619
+ populateItems(session, parts.items, parts.slots, parts.locations);
3620
+ populateVariables(session, parts.variables, {
3621
+ characters: parts.characters,
3622
+ items: parts.items,
3623
+ locations: parts.locations,
3624
+ values: void 0
3625
+ });
3626
+ return use(session);
3627
+ } finally {
3628
+ scratch.close();
3629
+ }
3630
+ }
3631
+ // src/host/checks/consistency.ts
3632
+ /** Words that name one thing a story tracks; a world that declares two of one group tracks it twice. */
3633
+ const SYNONYMS = [
3634
+ [
3635
+ "hp",
3636
+ "health",
3637
+ "hitpoints",
3638
+ "healthpoints",
3639
+ "life",
3640
+ "vitality"
3641
+ ],
3642
+ [
3643
+ "mp",
3644
+ "mana",
3645
+ "magicpoints",
3646
+ "magicpower"
3647
+ ],
3648
+ [
3649
+ "xp",
3650
+ "exp",
3651
+ "experience",
3652
+ "experiencepoints"
3653
+ ],
3654
+ [
3655
+ "gold",
3656
+ "money",
3657
+ "coins",
3658
+ "cash",
3659
+ "currency"
3660
+ ],
3661
+ [
3662
+ "stamina",
3663
+ "energy",
3664
+ "endurance"
3665
+ ],
3666
+ ["sanity", "san"],
3667
+ ["level", "lvl"]
3668
+ ];
3669
+ const squash = (text) => text.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "");
3670
+ /** The group of meaning a variable's key or name falls in: a synonym group, else the word itself. */
3671
+ const meanings = (def) => {
3672
+ const found = /* @__PURE__ */ new Set();
3673
+ for (const word of [def.key, def.name].map(squash).filter((word) => word !== "")) {
3674
+ const group = SYNONYMS.findIndex((names) => names.includes(word));
3675
+ found.add(group < 0 ? word : `group:${group}`);
3676
+ }
3677
+ return found;
3678
+ };
3679
+ const overlapping = (a, b) => {
3680
+ if (a.subject !== b.subject || a.kind !== b.kind) return false;
3681
+ const left = a.only ?? [];
3682
+ const right = b.only ?? [];
3683
+ return left.length === 0 || right.length === 0 || left.some((key) => right.includes(key));
3684
+ };
3685
+ /** Pairs of tracked values that mean the same thing for the same subjects. */
3686
+ function duplicateValues(defs) {
3687
+ const pairs = [];
3688
+ for (let i = 0; i < defs.length; i++) {
3689
+ const own = meanings(defs[i]);
3690
+ for (let j = i + 1; j < defs.length; j++) if (overlapping(defs[i], defs[j]) && [...meanings(defs[j])].some((meaning) => own.has(meaning))) pairs.push([defs[i], defs[j]]);
3691
+ }
3692
+ return pairs;
3693
+ }
3694
+ const asSkip = (error) => {
3695
+ if (error instanceof InvalidEditProblems) throw new CheckSkipped("other files of the world have problems that come first");
3696
+ throw error;
3697
+ };
3698
+ const consistencyChecks = [
3699
+ {
3700
+ id: "world-valid",
3701
+ kit: "consistency",
3702
+ mode: "code",
3703
+ needs: [],
3704
+ description: "Every file of the world reads and everything that refers to something refers to something that is there, as a story start checks it (it names the problems of the first part of the world that has any).",
3705
+ async run({ world }) {
3706
+ const check = await checkWorld(world);
3707
+ const found = check.problems.map((problem) => ({
3708
+ severity: "error",
3709
+ code: "invalid",
3710
+ where: problem.where,
3711
+ message: problem.message,
3712
+ hint: "Fix it, then run the check again: the next part of the world may have problems of its own."
3713
+ }));
3714
+ if (check.more > 0) found.push({
3715
+ severity: "error",
3716
+ code: "invalid",
3717
+ where: "(the world)",
3718
+ message: `${check.more} more problems are not listed`
3719
+ });
3720
+ return foundBy("world-valid", found);
3721
+ }
3722
+ },
3723
+ {
3724
+ id: "world-graph",
3725
+ kit: "consistency",
3726
+ mode: "code",
3727
+ needs: [],
3728
+ description: "Places no one can reach or leave, ways with no way back, a lock whose key does not exist, two characters, places or things with one name, characters nobody knows.",
3729
+ async run({ world }) {
3730
+ if (!(await checkWorld(world)).ok) throw new CheckSkipped("the world has problems that come first (see world-valid)");
3731
+ const parts = await loadWorldParts(world.directory).catch(asSkip);
3732
+ return foundBy("world-graph", withScratchStory(parts, (story) => lintWorld(story).map((finding) => ({
3733
+ severity: finding.severity,
3734
+ code: finding.code,
3735
+ where: `${finding.subject.kind}:${finding.subject.key}`,
3736
+ message: finding.message
3737
+ }))));
3738
+ }
3739
+ },
3740
+ {
3741
+ id: "duplicate-values",
3742
+ kit: "consistency",
3743
+ mode: "code",
3744
+ needs: [],
3745
+ description: "Tracked values that mean the same thing for the same subjects (health and hp), which the story would keep twice.",
3746
+ async run({ world }) {
3747
+ const { defs } = await loadVariables(world.directory);
3748
+ return foundBy("duplicate-values", duplicateValues(defs).map(([a, b]) => ({
3749
+ severity: "warning",
3750
+ code: "duplicate-value",
3751
+ where: "variables.json",
3752
+ message: `${a.key} (${a.name}) and ${b.key} (${b.name}) look like the same tracked value for the same ${a.subject}s`,
3753
+ hint: "Keep one and remove the other from variables.json and from the files that give it a starting value; which one is right is a choice."
3754
+ })));
3755
+ }
3756
+ },
3757
+ {
3758
+ id: "name-clashes",
3759
+ kit: "consistency",
3760
+ mode: "code",
3761
+ needs: [],
3762
+ description: "A character's alias that is another character's name or alias, two organisations or two lore entries with one name.",
3763
+ async run({ world }) {
3764
+ const [{ characters }, { factions }, { lore }] = await Promise.all([
3765
+ loadCharacters(world.directory),
3766
+ loadFactions(world.directory),
3767
+ loadLore(world.directory)
3768
+ ]);
3769
+ const found = [];
3770
+ const owners = /* @__PURE__ */ new Map();
3771
+ for (const character of characters) {
3772
+ const seen = /* @__PURE__ */ new Set();
3773
+ for (const label of [character.name, ...character.aliases]) {
3774
+ const word = squash(label);
3775
+ if (word === "" || seen.has(word)) continue;
3776
+ seen.add(word);
3777
+ const other = owners.get(word);
3778
+ if (other !== void 0 && other !== character.id) found.push({
3779
+ severity: "warning",
3780
+ code: "alias-clash",
3781
+ where: `characters/${character.id}`,
3782
+ message: `"${label}" names both ${other} and ${character.id}, so a mention cannot be told apart`,
3783
+ hint: "Give one of them a name or alias of its own."
3784
+ });
3785
+ else owners.set(word, character.id);
3786
+ }
3787
+ }
3788
+ const twice = (kind, entries) => {
3789
+ const seen = /* @__PURE__ */ new Map();
3790
+ for (const entry of entries) {
3791
+ const word = squash(entry.label);
3792
+ const other = seen.get(word);
3793
+ if (word !== "" && other !== void 0) found.push({
3794
+ severity: "warning",
3795
+ code: "name-twice",
3796
+ where: `${kind}/${entry.id}`,
3797
+ message: `${kind}/${other} and ${kind}/${entry.id} are both called "${entry.label}"`
3798
+ });
3799
+ else seen.set(word, entry.id);
3800
+ }
3801
+ };
3802
+ twice("factions", factions.map((entry) => ({
3803
+ id: entry.id,
3804
+ label: entry.name
3805
+ })));
3806
+ twice("lore", lore.map((entry) => ({
3807
+ id: entry.id,
3808
+ label: entry.title
3809
+ })));
3810
+ return foundBy("name-clashes", found);
3811
+ }
3812
+ },
3813
+ {
3814
+ id: "world-prompts",
3815
+ kit: "consistency",
3816
+ mode: "code",
3817
+ needs: [],
3818
+ description: "The prompts the world carries are prompts the product has, are not empty and use only the variables each is given: a world with a bad one cannot start a story.",
3819
+ async run({ world }) {
3820
+ const scratch = await mkdtemp(join(tmpdir(), "world-prompts-"));
3821
+ try {
3822
+ return foundBy("world-prompts", copyWorldPrompts(world.directory, scratch).map((problem) => ({
3823
+ severity: "error",
3824
+ code: "prompt",
3825
+ where: problem.path.slice(world.directory.length + 1) || problem.path,
3826
+ message: problem.message
3827
+ })));
3828
+ } finally {
3829
+ await rm(scratch, {
3830
+ recursive: true,
3831
+ force: true
3832
+ });
3833
+ }
3834
+ }
3835
+ }
3836
+ ];
3837
+ // src/host/import/card-diff.ts
3838
+ const MAX_SEGMENTS = 1500;
3839
+ const MAX_HUNK_CHARS = 700;
3840
+ /** Entries that kept neither their title nor their keys count as the same one only when this much of their words is shared. */
3841
+ const SAME_ENTRY = .5;
3842
+ const normalised = (text) => text.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
3843
+ const entryHead = (piece) => normalised([piece.title, ...piece.keys].join("|"));
3844
+ const words = (text) => new Set(text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []);
3845
+ function overlap$1(a, b) {
3846
+ const first = words(a);
3847
+ const second = words(b);
3848
+ if (first.size === 0 && second.size === 0) return 1;
3849
+ let shared = 0;
3850
+ for (const word of first) if (second.has(word)) shared += 1;
3851
+ return shared / (first.size + second.size - shared);
3852
+ }
3853
+ /**
3854
+ * Which piece of the old card is which piece of the new one. Fields and greetings are the same by their id; lorebook entries are numbered by position, which an edit
3855
+ * shifts, so they are found by what they are called and keyed on, then by their text, and only then by the number.
3856
+ */
3857
+ function matchPieces(before, after) {
3858
+ const pairs = [];
3859
+ const left = new Map(before.map((piece) => [piece.id, piece]));
3860
+ const right = new Map(after.map((piece) => [piece.id, piece]));
3861
+ const pair = (a, b) => {
3862
+ pairs.push({
3863
+ before: a,
3864
+ after: b
3865
+ });
3866
+ left.delete(a.id);
3867
+ right.delete(b.id);
3868
+ };
3869
+ const isEntry = (piece) => piece.id.startsWith("entry:");
3870
+ for (const piece of before) {
3871
+ const other = right.get(piece.id);
3872
+ if (!isEntry(piece) && other !== void 0) pair(piece, other);
3873
+ }
3874
+ const unmatched = (map) => [...map.values()].filter(isEntry);
3875
+ for (const keyOf of [entryHead, (piece) => normalised(piece.text)]) {
3876
+ const taken = /* @__PURE__ */ new Set();
3877
+ for (const piece of unmatched(left)) {
3878
+ const key = keyOf(piece);
3879
+ if (key === "" || key === "|") continue;
3880
+ const candidates = unmatched(right).filter((other) => !taken.has(other.id) && keyOf(other) === key);
3881
+ const same = candidates.find((other) => other.id === piece.id) ?? candidates[0];
3882
+ if (same !== void 0) {
3883
+ taken.add(same.id);
3884
+ pair(piece, same);
3885
+ }
3886
+ }
3887
+ }
3888
+ for (const piece of unmatched(left)) {
3889
+ const other = right.get(piece.id);
3890
+ if (other !== void 0 && overlap$1(piece.text, other.text) >= SAME_ENTRY) pair(piece, other);
3891
+ }
3892
+ const order = new Map(before.map((piece, index) => [piece.id, index]));
3893
+ return {
3894
+ pairs: pairs.sort((a, b) => (order.get(a.before.id) ?? 0) - (order.get(b.before.id) ?? 0)),
3895
+ added: [...right.values()],
3896
+ removed: [...left.values()]
3897
+ };
3898
+ }
3899
+ /** The sentences and lines of a text, each with the whitespace that follows it, so that joining them gives the text back. */
3900
+ function segments(text) {
3901
+ const parts = [];
3902
+ const endings = ".!?。!?\n";
3903
+ let start = 0;
3904
+ let at = 0;
3905
+ while (at < text.length) {
3906
+ if (!endings.includes(text[at])) {
3907
+ at += 1;
3908
+ continue;
3909
+ }
3910
+ while (at < text.length && endings.includes(text[at])) at += 1;
3911
+ while (at < text.length && /\s/u.test(text[at])) at += 1;
3912
+ parts.push(text.slice(start, at));
3913
+ start = at;
3914
+ }
3915
+ if (start < text.length) parts.push(text.slice(start));
3916
+ return parts;
3917
+ }
3918
+ const shorten = (text) => {
3919
+ const clean = text.replace(/\s+/g, " ").trim();
3920
+ return clean.length <= MAX_HUNK_CHARS ? clean : `${clean.slice(0, MAX_HUNK_CHARS)}…`;
3921
+ };
3922
+ /** Where two versions of a text differ, sentence by sentence; nothing when they are the same, and undefined when the texts are too long to compare (read both then). */
3923
+ function diffText(before, after) {
3924
+ if (before === after) return [];
3925
+ const a = segments(before).map((part) => part.trim());
3926
+ const b = segments(after).map((part) => part.trim());
3927
+ if (a.length > MAX_SEGMENTS || b.length > MAX_SEGMENTS) return void 0;
3928
+ const width = b.length + 1;
3929
+ const table = new Uint16Array((a.length + 1) * width);
3930
+ for (let i = a.length - 1; i >= 0; i -= 1) for (let j = b.length - 1; j >= 0; j -= 1) table[i * width + j] = a[i] === b[j] ? table[(i + 1) * width + j + 1] + 1 : Math.max(table[(i + 1) * width + j], table[i * width + j + 1]);
3931
+ const hunks = [];
3932
+ let i = 0;
3933
+ let j = 0;
3934
+ let last;
3935
+ let removed = [];
3936
+ let added = [];
3937
+ let before_;
3938
+ const close = () => {
3939
+ if (removed.length + added.length === 0) return;
3940
+ hunks.push({
3941
+ ...before_ === void 0 ? {} : { after: shorten(before_) },
3942
+ removed: shorten(removed.join(" ")),
3943
+ added: shorten(added.join(" "))
3944
+ });
3945
+ removed = [];
3946
+ added = [];
3947
+ };
3948
+ while (i < a.length || j < b.length) {
3949
+ if (i < a.length && j < b.length && a[i] === b[j]) {
3950
+ close();
3951
+ last = a[i];
3952
+ before_ = last;
3953
+ i += 1;
3954
+ j += 1;
3955
+ continue;
3956
+ }
3957
+ if (removed.length + added.length === 0) before_ = last;
3958
+ if (j < b.length && (i === a.length || table[i * width + j + 1] >= table[(i + 1) * width + j])) {
3959
+ added.push(b[j]);
3960
+ j += 1;
3961
+ } else {
3962
+ removed.push(a[i]);
3963
+ i += 1;
3964
+ }
3965
+ }
3966
+ close();
3967
+ return hunks;
3968
+ }
3969
+ /** What differs in what the card says about itself rather than in its pieces. */
3970
+ function cardChanges(before, after) {
3971
+ const lines = [];
3972
+ const compare = (label, a, b) => {
3973
+ if (a !== b) lines.push(`${label}: “${shorten(a)}” → “${shorten(b)}”`);
3974
+ };
3975
+ compare("name", before.name, after.name);
3976
+ compare("creator", before.creator, after.creator);
3977
+ compare("version", before.characterVersion, after.characterVersion);
3978
+ compare("tags", before.tags.join(", "), after.tags.join(", "));
3979
+ return lines;
3980
+ }
3981
+ /** What the newer card changes that the world keeps in its own file (the fields edit_world_info sets) rather than in a character, place, thing or entry. */
3982
+ function worldFieldChanges(before, after) {
3983
+ const changes = [];
3984
+ const differ = (a, b) => a.trim() !== b.trim();
3985
+ if (differ(before.card.description, after.card.description) || differ(before.card.scenario, after.card.scenario) || differ(before.card.creatorNotes, after.card.creatorNotes)) changes.push({
3986
+ field: "description",
3987
+ because: "the card's description, scenario or creator's notes changed, and the world's description summarises them"
3988
+ });
3989
+ if (before.card.tags.join("\n") !== after.card.tags.join("\n")) changes.push({
3990
+ field: "tags",
3991
+ because: `the card\'s tags are now: ${after.card.tags.join(", ") || "(none)"}; the world\'s tags follow them, and you add none of your own`
3992
+ });
3993
+ if (differ(before.card.creator, after.card.creator)) changes.push({
3994
+ field: "authorName",
3995
+ because: `the card\'s creator is now “${after.card.creator}”`
3996
+ });
3997
+ if (differ(openingText(before.card, before.choices.opening) ?? "", openingText(after.card, after.choices.opening) ?? "")) changes.push({
3998
+ field: "opening",
3999
+ because: "the greeting the world opens with changed; suggested is the new greeting as the import writes an opening (plain paragraphs, the card's markup removed, the player named by the world's player character where the card says {{user}})",
4000
+ suggested: openingMessage(openingText(after.card, after.choices.opening) ?? "", after.card.name)
4001
+ });
4002
+ if (JSON.stringify(alternateOpenings(before.card, before.choices.opening)) !== JSON.stringify(alternateOpenings(after.card, after.choices.opening))) changes.push({
4003
+ field: "alternateOpenings",
4004
+ because: "the card's other greetings changed; suggested is the whole list as the import writes it",
4005
+ suggested: alternateOpenings(after.card, after.choices.opening)
4006
+ });
4007
+ return changes;
4008
+ }
4009
+ // src/host/checks/world-text.ts
4010
+ /** Every string a document holds, joined: what the world says in it, without the structure around it. */
4011
+ const stringsOf = (value) => typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(stringsOf) : typeof value === "object" && value !== null ? Object.values(value).flatMap(stringsOf) : [];
4012
+ /** Fields that say what a document is or point at another document, not what the world says: a model comparing prose with a card is not shown them. */
4013
+ const STRUCTURE = /* @__PURE__ */ new Set([
4014
+ "id",
4015
+ "role",
4016
+ "tier",
4017
+ "kind",
4018
+ "scope",
4019
+ "type",
4020
+ "status",
4021
+ "control",
4022
+ "known_by",
4023
+ "related",
4024
+ "subjects",
4025
+ "sources",
4026
+ "to",
4027
+ "location",
4028
+ "parent",
4029
+ "held_by",
4030
+ "owner",
4031
+ "members",
4032
+ "knowledge",
4033
+ "relationships",
4034
+ "exits",
4035
+ "start",
4036
+ "visual_identity",
4037
+ "routine",
4038
+ "variables"
4039
+ ]);
4040
+ /** What a document says in words, one `field: text` line each, without the structure around it. */
4041
+ function proseOf(value, field = "") {
4042
+ if (typeof value === "string") return value.trim() === "" ? [] : [field === "" ? value : `${field}: ${value}`];
4043
+ if (Array.isArray(value)) return value.flatMap((entry) => proseOf(entry, field));
4044
+ if (typeof value === "object" && value !== null) return Object.entries(value).filter(([key]) => !STRUCTURE.has(key)).flatMap(([key, entry]) => proseOf(entry, key));
4045
+ return [];
4046
+ }
4047
+ async function readJson$1(file) {
4048
+ try {
4049
+ return JSON.parse(await readFile(file, "utf8"));
4050
+ } catch (error) {
4051
+ if (error.code === "ENOENT") return void 0;
4052
+ throw error;
4053
+ }
4054
+ }
4055
+ /** What the files of a world say, read afresh, for comparing with a card. A file that does not read is left out: the consistency kit names it. */
4056
+ async function readWorldText(directory) {
4057
+ const texts = /* @__PURE__ */ new Map();
4058
+ const prose = /* @__PURE__ */ new Map();
4059
+ const subjects = /* @__PURE__ */ new Map();
4060
+ const names = [];
4061
+ const KIND = {
4062
+ characters: "character",
4063
+ locations: "place",
4064
+ factions: "organisation",
4065
+ items: "thing",
4066
+ lore: "background entry"
4067
+ };
4068
+ for (const { directory: folder, file } of ENTITY_FOLDERS) for (const id of await subfolders(join(directory, folder))) {
4069
+ const document = await readJson$1(join(directory, folder, id, file)).catch(() => void 0);
4070
+ if (document === void 0 || typeof document !== "object") continue;
4071
+ texts.set(`${folder}/${id}`, stringsOf(document).join("\n"));
4072
+ prose.set(`${folder}/${id}`, proseOf(document).join("\n"));
4073
+ const label = document[folder === "lore" ? "title" : "name"];
4074
+ subjects.set(`${folder}/${id}`, `${KIND[folder]}${typeof label === "string" ? ` ${label}` : ""}`);
4075
+ if (folder !== "lore") {
4076
+ const own = [document["name"], ...Array.isArray(document["aliases"]) ? document["aliases"] : []].filter((name) => typeof name === "string" && name.trim() !== "");
4077
+ names.push({
4078
+ where: `${folder}/${id}`,
4079
+ kind: folder,
4080
+ names: own,
4081
+ playable: document["role"] === "playable"
4082
+ });
4083
+ }
4084
+ }
4085
+ const info = await readJson$1(join(directory, WORLD_FILE_NAME)).catch(() => void 0);
4086
+ if (typeof info === "object" && info !== null) for (const [field, value] of Object.entries(info)) {
4087
+ const text = stringsOf(value).join("\n");
4088
+ if (text.trim() !== "") {
4089
+ texts.set(`${WORLD_FILE_NAME}#${field}`, text);
4090
+ prose.set(`${WORLD_FILE_NAME}#${field}`, text);
4091
+ subjects.set(`${WORLD_FILE_NAME}#${field}`, `the world's ${field}`);
4092
+ }
4093
+ }
4094
+ const prompts = join(directory, PROMPTS_FOLDER);
4095
+ for (const language of await readdir(prompts).catch(() => [])) for (const id of listFiles(join(prompts, language))) texts.set(`${PROMPTS_FOLDER}/${language}/${id}`, await readFile(join(prompts, language, `${id}.md`), "utf8"));
4096
+ return {
4097
+ texts,
4098
+ prose,
4099
+ subjects,
4100
+ names
4101
+ };
4102
+ }
4103
+ // src/host/checks/fidelity.ts
4104
+ /** The most numbers one finding lists. */
4105
+ const NUMBERS_LISTED = 8;
4106
+ /** A changed passage of the new card is taken as reflected in the world when this much of its terms are in what was made from its piece. */
4107
+ const REFLECTED = .5;
4108
+ const MIN_PASSAGE_TERMS = 3;
4109
+ /** A piece with fewer terms than this is a phrase, not a source of facts: its absence proves nothing. */
4110
+ const MIN_PIECE_TERMS = 4;
4111
+ /** When this share of the checked names is missing from the card, it is the language or the whole card that differs, not each name. */
4112
+ const MOSTLY_MISSING = .5;
4113
+ const MIN_NAMES_FOR_PATTERN = 4;
4114
+ const SNIPPET = 120;
4115
+ const need$1 = (input) => {
4116
+ if (input.card === void 0) throw new CheckSkipped("the world has no card to compare with");
4117
+ return input.card;
4118
+ };
4119
+ const recordsNeeded = (evidence) => {
4120
+ const source = evidence.previous ?? evidence.source;
4121
+ if (source.records.classified === void 0 || source.records.roster === void 0) throw new CheckSkipped("the import left no record of what each piece was taken to be");
4122
+ };
4123
+ const snippet = (text) => `${text.replace(/\s+/gu, " ").trim().slice(0, SNIPPET)}${text.trim().length > SNIPPET ? "…" : ""}`;
4124
+ /** The pieces the import read for the world and the card the records are about. */
4125
+ const basis = (evidence) => evidence.previous ?? evidence.source;
4126
+ const coverage = {
4127
+ id: "card-coverage",
4128
+ kit: "fidelity",
4129
+ mode: "code",
4130
+ needs: ["card"],
4131
+ description: "Every piece of the card the import read for the world is in it somewhere: made into a character, place, organisation or thing, or into lore. A piece nothing comes from was lost or left out without a word.",
4132
+ async run(input) {
4133
+ const evidence = need$1(input);
4134
+ recordsNeeded(evidence);
4135
+ const source = basis(evidence);
4136
+ const made = madeInto(source, await readWorldText(input.world.directory));
4137
+ return foundBy("card-coverage", usedPieces(source).filter((piece) => termsOf(piece.text).size >= MIN_PIECE_TERMS && !made.has(baseId(piece.id))).map((piece) => ({
4138
+ severity: "warning",
4139
+ code: "piece-uncovered",
4140
+ where: `card:${piece.id}`,
4141
+ message: `${piece.label} (${piece.text.length} characters) was read for the world, but nothing in the world seems to be made from it`,
4142
+ hint: "Read it with card_read. If it says something about the world, add that where it belongs; if it is not meant for the story, say so."
4143
+ })));
4144
+ }
4145
+ };
4146
+ const names = {
4147
+ id: "card-names",
4148
+ kit: "fidelity",
4149
+ mode: "code",
4150
+ needs: ["card"],
4151
+ description: "Every character, place, organisation and thing of the world is named somewhere in the card (a made-up name is a fact the card does not give).",
4152
+ async run(input) {
4153
+ const evidence = need$1(input);
4154
+ const source = basis(evidence);
4155
+ const world = await readWorldText(input.world.directory);
4156
+ const text = folded([source.card.name, ...source.pieces.map((piece) => piece.text)].join("\n"));
4157
+ const named = (candidate) => {
4158
+ return [candidate, candidate.replace(/\s*[((][^))]*[))]/gu, "").trim()].some((name) => folded(name).trim() !== "" && text.includes(folded(name).trim()));
4159
+ };
4160
+ const checked = world.names.filter((thing) => !thing.playable && thing.names.length > 0);
4161
+ const missing = checked.filter((thing) => !thing.names.some(named));
4162
+ if (checked.length >= MIN_NAMES_FOR_PATTERN && missing.length / checked.length > MOSTLY_MISSING) return foundBy("card-names", [{
4163
+ severity: "info",
4164
+ code: "names-elsewhere",
4165
+ where: "(the world)",
4166
+ message: `${missing.length} of ${checked.length} names do not occur in the card: the world is probably in another language than the card, or was made from another card`,
4167
+ hint: "Compare by meaning instead; the judged checks do."
4168
+ }]);
4169
+ return foundBy("card-names", missing.map((thing) => ({
4170
+ severity: thing.kind === "items" ? "info" : "warning",
4171
+ code: "name-not-in-card",
4172
+ where: thing.where,
4173
+ message: `"${thing.names[0]}" does not occur anywhere in the card`,
4174
+ hint: "If the card never names it, it was made up: keep it only if the story needs it, and say it is not from the card."
4175
+ })));
4176
+ }
4177
+ };
4178
+ const NUMBER = /\p{N}{2,}(?:[.,:]\p{N}+)*/gu;
4179
+ /** The numbers of a piece's text, without those inside the card's macros and addresses. */
4180
+ function numbersOf(text) {
4181
+ const plain = text.replace(/\{\{[\s\S]*?\}\}/gu, " ").replace(/https?:\/\/\S+/gu, " ").normalize("NFKC");
4182
+ return [...new Set(plain.match(NUMBER) ?? [])];
4183
+ }
4184
+ const facts = {
4185
+ id: "card-numbers",
4186
+ kit: "fidelity",
4187
+ mode: "code",
4188
+ needs: ["card"],
4189
+ description: "The numbers a piece of the card gives (ages, years, amounts) are in the parts of the world made from it, as the card has them.",
4190
+ async run(input) {
4191
+ const evidence = need$1(input);
4192
+ recordsNeeded(evidence);
4193
+ const source = basis(evidence);
4194
+ const world = await readWorldText(input.world.directory);
4195
+ const made = madeInto(source, world);
4196
+ const found = [];
4197
+ for (const piece of usedPieces(source)) {
4198
+ const into = made.get(baseId(piece.id));
4199
+ if (into === void 0) continue;
4200
+ const said = into.map((where) => world.texts.get(where) ?? "").join("\n").normalize("NFKC");
4201
+ const lost = numbersOf(piece.text).filter((number) => !said.includes(number));
4202
+ if (lost.length > 0) found.push({
4203
+ severity: "info",
4204
+ code: "number-lost",
4205
+ where: `card:${piece.id}`,
4206
+ message: `${piece.label} gives ${lost.slice(0, NUMBERS_LISTED).join(", ")}${lost.length > NUMBERS_LISTED ? ` and ${lost.length - NUMBERS_LISTED} more` : ""}, which ${into.join(", ")} do not have`,
4207
+ hint: "Read the piece with card_read: a number that matters to the story belongs in the world as the card has it."
4208
+ });
4209
+ }
4210
+ return foundBy("card-numbers", found);
4211
+ }
4212
+ };
4213
+ /** Whether what was made from a piece (or, with none, the whole world) says a changed passage. */
4214
+ function reflected(passage, into, world) {
4215
+ const terms = termsOf(passage);
4216
+ if (terms.size < MIN_PASSAGE_TERMS) return true;
4217
+ return shareOf(terms, termsOf((into ?? [...world.texts.keys()]).map((where) => world.texts.get(where) ?? "").join("\n"))) >= REFLECTED;
4218
+ }
4219
+ const drift = {
4220
+ id: "card-update",
4221
+ kit: "fidelity",
4222
+ mode: "code",
4223
+ needs: ["card"],
4224
+ description: "With a newer card waiting: what the new card changed or added that the world does not say yet, and what only a dropped piece made.",
4225
+ async run(input) {
4226
+ const evidence = need$1(input);
4227
+ if (evidence.previous === void 0) throw new CheckSkipped("no newer card is waiting; ask for the card that is waiting with version new");
4228
+ recordsNeeded(evidence);
4229
+ const world = await readWorldText(input.world.directory);
4230
+ const made = madeInto(evidence.previous, world);
4231
+ const match = matchPieces(evidence.previous.pieces, evidence.source.pieces);
4232
+ const found = [];
4233
+ for (const { before, after } of match.pairs) {
4234
+ const hunks = diffText(before.text, after.text);
4235
+ const into = made.get(baseId(before.id));
4236
+ if (hunks === void 0) {
4237
+ found.push({
4238
+ severity: "info",
4239
+ code: "too-long-to-compare",
4240
+ where: `card:${after.id}`,
4241
+ message: `${after.label} is too long to compare sentence by sentence`,
4242
+ hint: "Read both versions with card_read (version current and new)."
4243
+ });
4244
+ continue;
4245
+ }
4246
+ for (const hunk of hunks) {
4247
+ if (hunk.added.trim() === "" || reflected(hunk.added, into, world)) continue;
4248
+ found.push({
4249
+ severity: "warning",
4250
+ code: "update-pending",
4251
+ where: `card:${after.id}`,
4252
+ message: `${after.label} now says “${snippet(hunk.added)}”, which the world does not seem to say yet${hunk.removed === "" ? "" : ` (it said “${snippet(hunk.removed)}”)`}`,
4253
+ hint: "Change what was made from this piece to match, keeping what the person edited."
4254
+ });
4255
+ }
4256
+ }
4257
+ const everything = [...world.texts.keys()];
4258
+ for (const piece of match.added.filter((entry) => entry.used && entry.enabled !== false)) if (!reflected(piece.text, everything, world)) found.push({
4259
+ severity: "info",
4260
+ code: "update-new-piece",
4261
+ where: `card:${piece.id}`,
4262
+ message: `${piece.label} is new in the card and the world does not seem to say it (it may be an instruction rather than the world)`
4263
+ });
4264
+ const kept = /* @__PURE__ */ new Map();
4265
+ for (const [piece, into] of made) for (const where of into) if (!match.removed.some((entry) => baseId(entry.id) === piece)) kept.set(where, (kept.get(where) ?? 0) + 1);
4266
+ for (const piece of match.removed) for (const where of made.get(baseId(piece.id)) ?? []) if (!kept.has(where)) found.push({
4267
+ severity: "info",
4268
+ code: "update-dropped",
4269
+ where,
4270
+ message: `${where} was made only from ${piece.label}, which the new card dropped`,
4271
+ hint: "Remove it unless the person edited it."
4272
+ });
4273
+ return foundBy("card-update", found);
4274
+ }
4275
+ };
4276
+ /** What one comparison is shown of the source, and how many documents one run compares: a card with more is compared largest source first and the rest is said. */
4277
+ const SOURCE_CHARS = 6e3;
4278
+ const MAX_COMPARED = 40;
4279
+ const MAX_REPORTED = 6;
4280
+ const FIDELITY_SCHEMA = {
4281
+ type: "object",
4282
+ properties: {
4283
+ dropped: {
4284
+ type: "array",
4285
+ items: {
4286
+ type: "object",
4287
+ properties: {
4288
+ fact: { type: "string" },
4289
+ quote: { type: "string" }
4290
+ },
4291
+ required: ["fact", "quote"],
4292
+ additionalProperties: false
4293
+ }
4294
+ },
4295
+ invented: {
4296
+ type: "array",
4297
+ items: {
4298
+ type: "object",
4299
+ properties: {
4300
+ fact: { type: "string" },
4301
+ quote: { type: "string" }
4302
+ },
4303
+ required: ["fact", "quote"],
4304
+ additionalProperties: false
4305
+ }
4306
+ }
4307
+ },
4308
+ required: ["dropped", "invented"],
4309
+ additionalProperties: false
4310
+ };
4311
+ const squashed = (text) => folded(text).replace(/\s+/gu, " ").trim();
4312
+ /** Why the comparison cannot be used: a quote that is not in the text it is said to come from is a guess, not a finding. */
4313
+ function comparisonProblem(value, source, document) {
4314
+ if (value.dropped.length > MAX_REPORTED || value.invented.length > MAX_REPORTED) return `report at most ${MAX_REPORTED} of each`;
4315
+ const missing = (list, text) => list.some((entry) => entry.fact.trim() === "" || !squashed(text).includes(squashed(entry.quote)) || squashed(entry.quote) === "");
4316
+ if (missing(value.dropped, source)) return "the quote of every dropped fact must be a passage of the source, exactly as it is written there";
4317
+ if (missing(value.invented, document)) return "the quote of every invented fact must be a passage of the document, exactly as it is written there";
4318
+ }
4319
+ const fidelityChecks = [
4320
+ coverage,
4321
+ names,
4322
+ facts,
4323
+ drift,
4324
+ {
4325
+ id: "card-fidelity",
4326
+ kit: "fidelity",
4327
+ mode: "judged",
4328
+ needs: ["card", "model"],
4329
+ description: "For each character, place, organisation, thing and background entry made from the card: facts the card states that the document lost, and facts the document states that the card does not give, each with the quoted passage.",
4330
+ async run(input) {
4331
+ const evidence = need$1(input);
4332
+ recordsNeeded(evidence);
4333
+ const model = input.model;
4334
+ const tr = trOf(model);
4335
+ const source = basis(evidence);
4336
+ const world = await readWorldText(input.world.directory);
4337
+ const made = madeInto(source, world, "about");
4338
+ const from = /* @__PURE__ */ new Map();
4339
+ for (const piece of usedPieces(source)) for (const where of made.get(baseId(piece.id)) ?? []) from.set(where, [...from.get(where) ?? [], piece]);
4340
+ const ranked = [...from].map(([where, pieces]) => ({
4341
+ where,
4342
+ pieces,
4343
+ size: pieces.reduce((sum, piece) => sum + piece.text.length, 0)
4344
+ })).sort((a, b) => b.size - a.size);
4345
+ const chosen = ranked.slice(0, MAX_COMPARED);
4346
+ const found = [];
4347
+ if (ranked.length > chosen.length) found.push({
4348
+ severity: "info",
4349
+ code: "not-compared",
4350
+ where: "(the world)",
4351
+ message: `${ranked.length - chosen.length} more documents were not compared: a run compares at most ${MAX_COMPARED}, the ones with the most source first`,
4352
+ hint: "Compare the rest with check_card again after fixing these, or read them against the card yourself."
4353
+ });
4354
+ await mapLimit(chosen, model.concurrency, async ({ where, pieces }) => {
4355
+ if (model.cancelled?.() === true) return;
4356
+ const document = world.prose.get(where) ?? "";
4357
+ const subject = world.subjects.get(where) ?? where;
4358
+ const text = pieces.map((piece) => `[${piece.label}]\n${piece.text.slice(0, SOURCE_CHARS)}`).join("\n\n").slice(0, SOURCE_CHARS * 2);
4359
+ try {
4360
+ const answer = await model.run({
4361
+ persona: model.text("checks/fidelity"),
4362
+ prompt: `${tr("Source pieces:")}\n${text}\n\n${tr("Document ({where}), about {subject}:", {
4363
+ where,
4364
+ subject
4365
+ })}\n${document}`,
4366
+ result: FIDELITY_SCHEMA,
4367
+ maxTokens: 1500,
4368
+ check: (value) => comparisonProblem(value, text, document)
4369
+ });
4370
+ const once = (list) => list.filter((entry, at) => list.findIndex((other) => squashed(other.quote) === squashed(entry.quote)) === at);
4371
+ for (const entry of once(answer.dropped)) found.push({
4372
+ severity: "warning",
4373
+ code: "fact-dropped",
4374
+ where,
4375
+ message: `the card says “${snippet(entry.quote)}” (${entry.fact}), which ${where} does not say`,
4376
+ hint: "Read the piece with card_read; if the fact matters to the story, add it to the document as the card has it."
4377
+ });
4378
+ for (const entry of once(answer.invented)) found.push({
4379
+ severity: "warning",
4380
+ code: "fact-invented",
4381
+ where,
4382
+ message: `${where} says “${snippet(entry.quote)}” (${entry.fact}), which the card does not give`,
4383
+ hint: "Remove it unless the person wants it; the world should not state what its source does not."
4384
+ });
4385
+ } catch (error) {
4386
+ if (model.cancelled?.() === true) throw error;
4387
+ found.push({
4388
+ severity: "info",
4389
+ code: "not-compared",
4390
+ where,
4391
+ message: `${where} could not be compared: ${error instanceof Error ? error.message : String(error)}`
4392
+ });
4393
+ }
4394
+ });
4395
+ return foundBy("card-fidelity", found);
4396
+ }
4397
+ }
4398
+ ];
4399
+ // src/host/worlds/world-info.ts
4400
+ const textOf = (value) => typeof value === "string" ? value : "";
4401
+ const toolsOf = (value) => {
4402
+ const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
4403
+ return typeof board === "string" ? {} : board;
4404
+ };
4405
+ function infoOf(document) {
4406
+ const opening = document["opening_message"];
4407
+ const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
4408
+ const plain = typeof opening === "string" ? opening : Array.isArray(opening) ? opening.map((part) => textOf(part?.["text"])).filter((text) => text !== "").join("\n\n") : "";
4409
+ const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
4410
+ const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
4411
+ const rules = document["rules"];
4412
+ return {
4413
+ name: textOf(document["name"]),
4414
+ description: textOf(document["description"]),
4415
+ tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
4416
+ rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
4417
+ opening: plain,
4418
+ openingParts: parts,
4419
+ authorName: textOf(author["name"]),
4420
+ authorUrl: textOf(author["url"]),
4421
+ timeZone: textOf(document["time_zone"]),
4422
+ startingTime: textOf(document["starting_time"]),
4423
+ preset: textOf(document["preset"]),
4424
+ lorebooks: Array.isArray(document["lorebooks"]) ? document["lorebooks"].filter((name) => typeof name === "string") : [],
4425
+ version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
4426
+ sampling: parseSampling(document["sampling"], "sampling", []),
4427
+ tools: toolsOf(document["tools"]),
4428
+ alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
4429
+ title: textOf(entry["title"]),
4430
+ text: entry["text"],
4431
+ ...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
4432
+ }] : []) : []
4433
+ };
4434
+ }
4435
+ async function readDocument(directory) {
4436
+ const text = await readFile(join(directory, WORLD_FILE_NAME), "utf8");
4437
+ return {
4438
+ text,
4439
+ document: JSON.parse(text.replace(/^/, ""))
4440
+ };
4441
+ }
4442
+ async function readWorldInfo(directory) {
4443
+ return infoOf((await readDocument(directory)).document);
4444
+ }
4445
+ function setOrRemove(document, key, value) {
4446
+ if (value === "") delete document[key];
4447
+ else document[key] = value;
4448
+ }
4449
+ /**
4450
+ * Changes the fields of `world.json` the edit names and nothing else, keeping the file's other fields and its indentation. The result is read
4451
+ * back as the world will be read before it is written.
4452
+ * @throws {InvalidEditProblems} when the world would no longer be valid.
4453
+ */
4454
+ function editWorldInfo(directory, edit) {
4455
+ return serialized(directory, () => changeWorldInfo(directory, edit));
4456
+ }
4457
+ async function changeWorldInfo(directory, edit) {
4458
+ const { text, document } = await readDocument(directory);
4459
+ const before = infoOf(document);
4460
+ if (edit.opening !== void 0 && before.openingParts && edit.opening !== before.opening) throw new InvalidEditProblems(["the opening has lines spoken by characters: change it in the file, or ask the authoring assistant"]);
4461
+ if (edit.name !== void 0) document["name"] = edit.name;
4462
+ if (edit.description !== void 0) document["description"] = edit.description;
4463
+ if (edit.tags !== void 0) document["metadata"] = {
4464
+ ...typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {},
4465
+ tags: edit.tags
4466
+ };
4467
+ if (edit.rules !== void 0) {
4468
+ if (edit.rules.length === 0) delete document["rules"];
4469
+ else document["rules"] = edit.rules;
4470
+ }
4471
+ if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
4472
+ if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
4473
+ const name = edit.authorName ?? before.authorName;
4474
+ const url = edit.authorUrl ?? before.authorUrl;
4475
+ if (name === "" && url !== "") throw new InvalidEditProblems(["an author link needs the author's name"]);
4476
+ if (name === "") delete document["author"];
4477
+ else document["author"] = {
4478
+ ...typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {},
4479
+ name,
4480
+ ...url === "" ? {} : { url }
4481
+ };
4482
+ if (url === "" && typeof document["author"] === "object") delete document["author"]["url"];
4483
+ }
4484
+ if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
4485
+ if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
4486
+ if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
4487
+ if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
4488
+ if (edit.lorebooks !== void 0) {
4489
+ if (edit.lorebooks.length === 0) delete document["lorebooks"];
4490
+ else document["lorebooks"] = edit.lorebooks;
4491
+ }
4492
+ if (edit.alternateOpenings !== void 0) {
4493
+ if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
4494
+ else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
4495
+ title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
4496
+ text: entry.text,
4497
+ ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
4498
+ }));
4499
+ }
4500
+ if (edit.sampling !== void 0) {
4501
+ if (Object.keys(edit.sampling).length === 0) delete document["sampling"];
4502
+ else document["sampling"] = edit.sampling;
4503
+ }
4504
+ if (edit.tools !== void 0) {
4505
+ if (Object.keys(edit.tools).length === 0) delete document["tools"];
4506
+ else document["tools"] = edit.tools;
4507
+ }
4508
+ const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
4509
+ const parsed = parseWorldFile(next);
4510
+ if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
4511
+ await atomicWrite(join(directory, WORLD_FILE_NAME), next);
4512
+ return infoOf(document);
4513
+ }
4514
+ // src/host/checks/judge.ts
4515
+ /**
4516
+ * A yes-or-no about one thing: the decision model answers when the import is set to use one and it is sure; when it is not sure, cannot be used, or none is set, `ask` puts the
4517
+ * question to the language model. The decision model is never the only reader of a thing that may be wrong.
4518
+ */
4519
+ async function verdictOf(model, state, key, instructions, ask) {
4520
+ if (model.decide !== void 0) try {
4521
+ const probability = (await model.decide(state, [{
4522
+ key,
4523
+ instructions
4524
+ }])).get(key);
4525
+ const confidence = model.confidence ?? .7;
4526
+ if (probability !== void 0 && probability >= yesAt(confidence)) return {
4527
+ yes: true,
4528
+ by: "decision"
4529
+ };
4530
+ if (probability !== void 0 && probability <= noAt(confidence)) return {
4531
+ yes: false,
4532
+ by: "decision"
4533
+ };
4534
+ } catch (error) {
4535
+ if (model.cancelled?.() === true) throw error;
4536
+ }
4537
+ return {
4538
+ yes: await ask(),
4539
+ by: "language"
4540
+ };
4541
+ }
4542
+ // src/host/checks/quality.ts
4543
+ /** A place described in fewer characters than this has nothing to play with. */
4544
+ const THIN_PLACE = 20;
4545
+ const SHEET_CHARS = 3e3;
4546
+ const DIGEST_CHARS = 7e3;
4547
+ const GAPS_LISTED = 8;
4548
+ const text = (value) => (value ?? "").trim();
4549
+ const cast = {
4550
+ id: "quality-cast",
4551
+ kit: "quality",
4552
+ mode: "code",
4553
+ needs: [],
4554
+ description: "Whether the cast can be played: someone to play, sheets with more than a summary for the characters that matter, voices, and characters that are one description twice.",
4555
+ async run({ world }) {
4556
+ const { characters } = await loadCharacters(world.directory);
4557
+ if (characters.length === 0) throw new CheckSkipped("the world has no characters yet");
4558
+ const found = [];
4559
+ if (!characters.some((character) => character.role === "playable")) found.push({
4560
+ severity: "warning",
4561
+ code: "no-playable",
4562
+ where: "characters",
4563
+ message: "no character can be played, so a story from this world needs an avatar brought along",
4564
+ hint: "Make one character playable, or add one for the player."
4565
+ });
4566
+ const seen = /* @__PURE__ */ new Map();
4567
+ for (const character of characters) {
4568
+ const where = `characters/${character.id}`;
4569
+ const main = character.tier !== "background" && character.kind === "person";
4570
+ if (main && text(character.personality) === "" && text(character.background) === "" && text(character.speech.style) === "") found.push({
4571
+ severity: "warning",
4572
+ code: "sheet-summary-only",
4573
+ where,
4574
+ message: `${character.name} has only a summary: no personality, background or way of speaking`,
4575
+ hint: "Write from what the card or the world says about them; do not make them up."
4576
+ });
4577
+ else if (main && text(character.speech.style) === "" && character.speech.examples.length === 0) found.push({
4578
+ severity: "info",
4579
+ code: "no-voice",
4580
+ where,
4581
+ message: `${character.name} has no stated way of speaking`
4582
+ });
4583
+ const summary = norm(character.summary);
4584
+ if (summary !== "") {
4585
+ const other = seen.get(summary);
4586
+ if (other !== void 0) found.push({
4587
+ severity: "warning",
4588
+ code: "same-summary",
4589
+ where,
4590
+ message: `${character.name} and ${other} have the same summary, so they may be one character written twice`,
4591
+ hint: "Merge them, or tell them apart."
4592
+ });
4593
+ else seen.set(summary, character.name);
4594
+ }
4595
+ }
4596
+ return foundBy("quality-cast", found);
4597
+ }
4598
+ };
4599
+ const places = {
4600
+ id: "quality-places",
4601
+ kit: "quality",
4602
+ mode: "code",
4603
+ needs: [],
4604
+ description: "Places with no description, or one too short to play in.",
4605
+ async run({ world }) {
4606
+ const { locations } = await loadLocations(world.directory);
4607
+ return foundBy("quality-places", locations.flatMap((place) => {
4608
+ const length = text(place.description).length;
4609
+ if (length === 0) return [{
4610
+ severity: "warning",
4611
+ code: "place-undescribed",
4612
+ where: `locations/${place.id}`,
4613
+ message: `${place.name} has no description`
4614
+ }];
4615
+ return length < THIN_PLACE && place.features.length === 0 ? [{
4616
+ severity: "info",
4617
+ code: "place-thin",
4618
+ where: `locations/${place.id}`,
4619
+ message: `${place.name} has a one-line description and no features`
4620
+ }] : [];
4621
+ }));
4622
+ }
4623
+ };
4624
+ const about = {
4625
+ id: "quality-world",
4626
+ kit: "quality",
4627
+ mode: "code",
4628
+ needs: [],
4629
+ description: "What the world says about itself: a description, tags for the catalogue, an opening for the story.",
4630
+ async run({ world }) {
4631
+ const info = await readWorldInfo(world.directory);
4632
+ const found = [];
4633
+ if (text(info.description) === "") found.push({
4634
+ severity: "info",
4635
+ code: "no-description",
4636
+ where: "world.json",
4637
+ message: "the world has no description, so the worlds list shows nothing about it"
4638
+ });
4639
+ if (info.tags.length === 0) found.push({
4640
+ severity: "info",
4641
+ code: "no-tags",
4642
+ where: "world.json",
4643
+ message: "the world has no tags"
4644
+ });
4645
+ if (text(info.opening) === "" && !info.openingParts) found.push({
4646
+ severity: "info",
4647
+ code: "no-opening",
4648
+ where: "world.json",
4649
+ message: "the world has no opening, so a story starts with \"The story begins.\""
4650
+ });
4651
+ return foundBy("quality-world", found);
4652
+ }
4653
+ };
4654
+ const SHEET_SCHEMA = {
4655
+ type: "object",
4656
+ properties: {
4657
+ reason: { type: "string" },
4658
+ playable: { type: "boolean" }
4659
+ },
4660
+ required: ["reason", "playable"],
4661
+ additionalProperties: false
4662
+ };
4663
+ const sheets = {
4664
+ id: "sheet-playable",
4665
+ kit: "quality",
4666
+ mode: "decision",
4667
+ needs: ["model"],
4668
+ description: "Whether each principal or supporting character's sheet is enough to play them (who they are, how they talk, what they want). A decision model may answer; what it is unsure of goes to the language model.",
4669
+ async run({ world, model }) {
4670
+ const { characters } = await loadCharacters(world.directory);
4671
+ const asked = characters.filter((character) => character.tier !== "background" && character.kind === "person");
4672
+ const found = [];
4673
+ await mapLimit(asked, model.concurrency, async (character) => {
4674
+ const sheet = [
4675
+ `name: ${character.name}`,
4676
+ `summary: ${character.summary}`,
4677
+ `personality: ${character.personality}`,
4678
+ `background: ${character.background}`,
4679
+ `speech: ${character.speech.style}`,
4680
+ ...character.speech.examples.slice(0, 3).map((example) => `says: ${example}`),
4681
+ ...(character.start.intents ?? []).slice(0, 3).map((intent) => `wants: ${intent.name}: ${intent.description}`)
4682
+ ].join("\n").slice(0, SHEET_CHARS);
4683
+ let reason = "";
4684
+ const instructions = model.text("checks/decide-sheet");
4685
+ if (!(await verdictOf(model, { sheet }, "playable", instructions, async () => {
4686
+ const answer = await model.run({
4687
+ persona: instructions,
4688
+ prompt: sheet,
4689
+ result: SHEET_SCHEMA,
4690
+ maxTokens: 500
4691
+ });
4692
+ reason = answer.reason;
4693
+ return answer.playable;
4694
+ })).yes) found.push({
4695
+ severity: "warning",
4696
+ code: "sheet-thin",
4697
+ where: `characters/${character.id}`,
4698
+ message: `${character.name}'s sheet is not enough to play them${reason === "" ? "" : `: ${reason}`}`,
4699
+ hint: "Fill it in from the card or the world, or ask the person; do not make them up."
4700
+ });
4701
+ });
4702
+ return foundBy("sheet-playable", found);
4703
+ }
4704
+ };
4705
+ const GAPS_SCHEMA = {
4706
+ type: "object",
4707
+ properties: { gaps: {
4708
+ type: "array",
4709
+ items: {
4710
+ type: "object",
4711
+ properties: {
4712
+ about: { type: "string" },
4713
+ gap: { type: "string" },
4714
+ fill: { type: "string" }
4715
+ },
4716
+ required: [
4717
+ "about",
4718
+ "gap",
4719
+ "fill"
4720
+ ],
4721
+ additionalProperties: false
4722
+ }
4723
+ } },
4724
+ required: ["gaps"],
4725
+ additionalProperties: false
4726
+ };
4727
+ const qualityChecks = [
4728
+ cast,
4729
+ places,
4730
+ about,
4731
+ sheets,
4732
+ {
4733
+ id: "world-gaps",
4734
+ kit: "quality",
4735
+ mode: "judged",
4736
+ needs: ["model"],
4737
+ description: "What a model reading a digest of the world finds missing for it to play well: places with nothing to do, conflicts nobody carries, openings the world never sets up.",
4738
+ async run({ world, model }) {
4739
+ const [{ characters }, { locations }, { factions }, { lore }, { defs }] = await Promise.all([
4740
+ loadCharacters(world.directory),
4741
+ loadLocations(world.directory),
4742
+ loadFactions(world.directory),
4743
+ loadLore(world.directory),
4744
+ loadVariables(world.directory)
4745
+ ]);
4746
+ const named = /* @__PURE__ */ new Map();
4747
+ for (const [kind, entries] of [
4748
+ ["character", characters.map((entry) => ({
4749
+ id: entry.id,
4750
+ name: entry.name
4751
+ }))],
4752
+ ["place", locations.map((entry) => ({
4753
+ id: entry.id,
4754
+ name: entry.name
4755
+ }))],
4756
+ ["organisation", factions.map((entry) => ({
4757
+ id: entry.id,
4758
+ name: entry.name
4759
+ }))],
4760
+ ["background", lore.map((entry) => ({
4761
+ id: entry.id,
4762
+ name: entry.title
4763
+ }))]
4764
+ ]) for (const entry of entries) for (const label of [
4765
+ entry.id,
4766
+ entry.name,
4767
+ `${kind} ${entry.id}`,
4768
+ `${kind} ${entry.name}`
4769
+ ]) named.set(norm(label), entry.id);
4770
+ /** What the model named, as the key of that thing; anything else is about the world as a whole. */
4771
+ const keyOf = (about) => named.get(norm(about)) ?? "(the world)";
4772
+ const digest = [
4773
+ `world: ${world.summary.name}: ${text((await readWorldInfo(world.directory)).description)}`,
4774
+ ...characters.map((entry) => `character ${entry.id} (${entry.role}, ${entry.tier}): ${entry.name}: ${entry.summary}`),
4775
+ ...locations.map((entry) => `place ${entry.id}: ${entry.name}: ${text(entry.description).slice(0, 160)} (${entry.exits.length} ways out)`),
4776
+ ...factions.map((entry) => `organisation ${entry.id}: ${entry.name}: ${entry.summary}`),
4777
+ ...lore.map((entry) => `background ${entry.id}: ${entry.title}: ${entry.summary}`),
4778
+ ...defs.length === 0 ? [] : [`tracked values: ${defs.map((def) => def.key).join(", ")}`]
4779
+ ].join("\n").slice(0, DIGEST_CHARS);
4780
+ const answer = await model.run({
4781
+ persona: model.text("checks/gaps"),
4782
+ prompt: digest,
4783
+ result: GAPS_SCHEMA,
4784
+ maxTokens: 1500,
4785
+ check: (value) => value.gaps.length > GAPS_LISTED ? `name at most ${GAPS_LISTED} gaps` : value.gaps.some((gap) => text(gap.gap) === "" || text(gap.fill) === "") ? "every gap says what is missing and what would fill it" : void 0
4786
+ });
4787
+ return foundBy("world-gaps", answer.gaps.map((gap) => ({
4788
+ severity: "info",
4789
+ code: "gap",
4790
+ where: keyOf(gap.about),
4791
+ message: gap.gap,
4792
+ hint: gap.fill
4793
+ })));
4794
+ }
4795
+ }
4796
+ ];
4797
+ // src/host/checks/results.ts
4798
+ /** Where a world keeps what its checks found: a dot folder, so what is published leaves it out, like the import's. */
4799
+ const CHECKS_FOLDER = ".checks";
4800
+ const FILE = "results.json";
4801
+ async function read(directory) {
4802
+ try {
4803
+ const stored = JSON.parse(await readFile(join(directory, CHECKS_FOLDER, FILE), "utf8"));
4804
+ return stored.version === 1 && typeof stored.checks === "object" && stored.checks !== null ? stored : {
4805
+ version: 1,
4806
+ checks: {}
4807
+ };
4808
+ } catch (error) {
4809
+ if (error.code === "ENOENT" || error instanceof SyntaxError) return {
4810
+ version: 1,
4811
+ checks: {}
4812
+ };
4813
+ throw error;
4814
+ }
4815
+ }
4816
+ /**
4817
+ * Stores the findings of the checks that ran, replacing their last ones, and says what changed against those: results of checks that did not run stay.
4818
+ * @returns `undefined` when none of these checks had run before.
4819
+ */
4820
+ async function recordResults(directory, at, results) {
4821
+ const stored = await read(directory);
4822
+ const before = Object.keys(results).flatMap((id) => stored.checks[id]?.findings ?? []);
4823
+ const known = Object.keys(results).some((id) => stored.checks[id] !== void 0);
4824
+ const now = Object.values(results).flat();
4825
+ const was = new Set(before.map(findingKey));
4826
+ const is = new Set(now.map(findingKey));
4827
+ for (const [id, findings] of Object.entries(results)) stored.checks[id] = {
4828
+ at,
4829
+ findings
4830
+ };
4831
+ await atomicWrite(join(directory, CHECKS_FOLDER, FILE), JSON.stringify(stored, null, 2), { createDirectory: true });
4832
+ return known ? {
4833
+ added: now.filter((finding) => !was.has(findingKey(finding))).length,
4834
+ resolved: before.filter((finding) => !is.has(findingKey(finding)))
4835
+ } : void 0;
4836
+ }
4837
+ // src/host/checks/run.ts
4838
+ /** Every check of the suite, grouped by kit; the kits are the unit a command or a tool asks for. */
4839
+ const CHECKS = [
4840
+ ...consistencyChecks,
4841
+ ...fidelityChecks,
4842
+ ...qualityChecks
4843
+ ];
4844
+ const checksOf = (kits, checks = CHECKS) => checks.filter((check) => kits.includes(check.kit));
4845
+ /**
4846
+ * Runs the checks asked for in order (a check that cannot run on this world, or lacks what it needs, is listed as skipped with the reason), stores what each found and
4847
+ * reports it with what changed since the checks last ran.
4848
+ */
4849
+ async function runChecks(input, run = {}, checks = CHECKS, now = () => /* @__PURE__ */ new Date()) {
4850
+ const kits = run.kits ?? KITS;
4851
+ const chosen = checksOf(kits, checks).filter((check) => run.ids === void 0 || run.ids.includes(check.id));
4852
+ const results = {};
4853
+ const skipped = [];
4854
+ for (const check of chosen) {
4855
+ if (check.mode !== "code" && run.deep !== true) {
4856
+ skipped.push({
4857
+ check: check.id,
4858
+ reason: "judged by a model: ask for a deep check to run it"
4859
+ });
4860
+ continue;
4861
+ }
4862
+ const missing = check.needs.find((need) => input[need] === void 0);
4863
+ if (missing !== void 0) {
4864
+ skipped.push({
4865
+ check: check.id,
4866
+ reason: missing === "card" ? "the world has no card to compare with" : "no model is available to judge"
4867
+ });
4868
+ continue;
4869
+ }
4870
+ try {
4871
+ results[check.id] = await check.run(input);
4872
+ } catch (error) {
4873
+ if (input.model?.cancelled?.() === true) throw error;
4874
+ skipped.push({
4875
+ check: check.id,
4876
+ reason: error instanceof CheckSkipped ? error.message : `it failed: ${error instanceof Error ? error.message : String(error)}`
4877
+ });
4878
+ }
4879
+ }
4880
+ const at = now().toISOString();
4881
+ const changes = await recordResults(input.world.directory, at, results);
4882
+ const findings = Object.values(results).flat().sort((a, b) => SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity));
4883
+ return {
4884
+ at,
4885
+ kits: [...kits],
4886
+ ran: Object.keys(results),
4887
+ skipped,
4888
+ findings,
4889
+ ...changes === void 0 ? {} : { changes }
4890
+ };
4891
+ }
4892
+ // src/host/checks/present.ts
4893
+ /** The most findings a tool result lists: the rest are counted. */
4894
+ const LISTED = 40;
4895
+ const RESOLVED_LISTED = 10;
4896
+ /** What the assistant reads of a report: counts first, the worst findings, then what changed since the last run. */
4897
+ function presentReport(report) {
4898
+ const count = (severity) => report.findings.filter((finding) => finding.severity === severity).length;
4899
+ return {
4900
+ ok: count("error") === 0,
4901
+ counts: Object.fromEntries(SEVERITIES.map((severity) => [severity, count(severity)])),
4902
+ findings: report.findings.slice(0, LISTED),
4903
+ more: Math.max(0, report.findings.length - LISTED),
4904
+ skipped: report.skipped,
4905
+ ...report.changes === void 0 ? {} : { since_last_run: {
4906
+ new: report.changes.added,
4907
+ resolved: report.changes.resolved.slice(0, RESOLVED_LISTED),
4908
+ resolved_count: report.changes.resolved.length
4909
+ } }
4910
+ };
4911
+ }
4912
+ // src/host/checks/imported.ts
4913
+ /**
4914
+ * What every import and update is checked with when it is written: all the checks the program decides, against the card the world now comes from, stored with the world. The
4915
+ * checks a model judges are not run here: the assistant that reviews the import asks for them (`deep`) when the card and these findings call for it.
4916
+ * @returns what the assistant reads of the report.
4917
+ */
4918
+ async function checkImported(directory, name) {
4919
+ const card = await loadCardEvidence(directory, "current");
4920
+ return presentReport(await runChecks({
4921
+ world: {
4922
+ directory,
4923
+ summary: { name }
4924
+ },
4925
+ ...card === void 0 ? {} : { card }
4926
+ }, { kits: KITS }));
4927
+ }
4928
+ // src/host/import/run-import.ts
3025
4929
  /** The import in a world is not in the state the step needs, or there is none. The message says what to do. */
3026
4930
  var ImportStateError = class extends Error {};
3027
4931
  const PHASES = [
@@ -3258,11 +5162,61 @@ async function finish(ctx, world) {
3258
5162
  counts: result.report.counts,
3259
5163
  notes: result.report.notes.length
3260
5164
  }, await readFile(join(folder(world), "card.json"), "utf8"));
5165
+ return {
5166
+ ...result,
5167
+ checks: await checkImported(world, choices.name)
5168
+ };
3261
5169
  }
3262
5170
  return result;
3263
5171
  }
3264
- //#endregion
3265
- //#region src/host/import/tools.ts
5172
+ /**
5173
+ * Imports the card waiting in a world without a model: what {@link structureOnly} lays out is written as the world, with no review after it. A world that would not start yet is left a draft, which the person
5174
+ * can keep, discard or have an assistant repair.
5175
+ */
5176
+ async function structureImport(world, language) {
5177
+ await need(world, ["ready"], "the import without a model");
5178
+ const { card, choices, items, picture } = await load(world);
5179
+ const { classified, roster, extracted } = structureOnly(card, items, choices);
5180
+ const pictures = await ensurePictures(world, card.urls ?? []);
5181
+ const result = await finishImport({
5182
+ noModel: true,
5183
+ run: () => Promise.reject(/* @__PURE__ */ new Error("this import has no model")),
5184
+ concurrency: 1,
5185
+ text: (id, variables) => shippedText(id, language ?? "en", variables),
5186
+ say: () => void 0,
5187
+ ...language === void 0 ? {} : { language }
5188
+ }, {
5189
+ directory: world,
5190
+ card,
5191
+ choices,
5192
+ roster,
5193
+ items,
5194
+ classified,
5195
+ extracted,
5196
+ ...picture ? { picture: await readFile(join(folder(world), PICTURE_FILE)) } : {},
5197
+ notes: [],
5198
+ pictures: {
5199
+ found: pictures.found,
5200
+ added: pictures.added.length
5201
+ }
5202
+ });
5203
+ if (!result.ok) throw new ImportStateError(`the card could not be written as a world: ${result.problems.join("; ")}`);
5204
+ if (result.draft === void 0) await finishedImport(world);
5205
+ else await writeJson(join(folder(world), STATE), { phase: "repair" });
5206
+ await recordProvenance(world, {
5207
+ kind: "import",
5208
+ card: { name: card.name },
5209
+ language: language ?? "",
5210
+ counts: result.report.counts,
5211
+ notes: result.report.notes.length
5212
+ }, await readFile(join(folder(world), "card.json"), "utf8"));
5213
+ await checkImported(world, choices.name);
5214
+ return {
5215
+ report: result.report,
5216
+ ...result.draft === void 0 ? {} : { draft: result.draft }
5217
+ };
5218
+ }
5219
+ // src/host/import/tools.ts
3266
5220
  const SURVEY_TOOL = "import_survey";
3267
5221
  const BUILD_TOOL = "import_build";
3268
5222
  const FINISH_TOOL = "import_finish";
@@ -3294,33 +5248,55 @@ const output = (render) => ({
3294
5248
  }]
3295
5249
  });
3296
5250
  const json = (value) => JSON.parse(JSON.stringify(value));
5251
+ /** What an endpoint says when it will not take `response_format` with a JSON schema. */
5252
+ const SCHEMA_REFUSED = /response_format|json_schema|Extra inputs are not permitted|unknown (?:field|parameter)/i;
5253
+ /** The models (`provider/model`) found not to take a JSON schema: they are asked for their result by a tool call. */
5254
+ const refusesSchema = /* @__PURE__ */ new Set();
5255
+ /** The model a helper runs on, as `provider/model`: the one named in the settings, else the chat's own. */
5256
+ function modelKeyOf(agent, named) {
5257
+ const config = agent?.session.requestHeader()?.config;
5258
+ const model = named ?? (config?.provider === void 0 || config.model === void 0 ? void 0 : {
5259
+ provider: config.provider,
5260
+ model: config.model
5261
+ });
5262
+ return model === void 0 ? "" : `${model.provider}/${model.model}`;
5263
+ }
3297
5264
  /** The runner of an import: every job is a narrow agent below the chat's own, on the chat's model. */
3298
5265
  function contextOf(exec, settings, text, language) {
3299
5266
  const agent = exec.agent;
3300
5267
  if (agent === void 0) throw new Error("the import tools can only be called by an agent");
3301
5268
  const run = async (job) => {
3302
- for (let attempt = 1;; attempt += 1) try {
5269
+ for (let attempt = 1;; attempt += 1) {
3303
5270
  const named = namedModel(settings.model);
3304
- const ceiling = await outputCeiling(settings.maxTokens, agent, named.model, exec.signal);
3305
- return await runChild({
3306
- parent: agent,
3307
- signal: exec.signal,
3308
- persona: job.persona,
3309
- prompt: job.prompt,
3310
- result: job.result,
3311
- ...job.check === void 0 ? {} : { beforeSubmit: (value) => job.check?.(value) },
3312
- maxTokens: Math.min((job.maxTokens ?? ceiling) + ANALYSIS_TOKENS, ceiling),
3313
- timeoutMinutes: settings.timeoutMinutes,
3314
- ...named,
3315
- ...settings.structured === "schema" ? { structured: true } : {},
3316
- sampling: {
3317
- temperature: settings.temperature,
3318
- toolChoice: "required"
3319
- },
3320
- ...settings.reasoning === "" ? {} : { reasoningEffort: settings.reasoning }
3321
- });
3322
- } catch (error) {
3323
- if (exec.signal.aborted || attempt >= ATTEMPTS || error instanceof ChildTimeoutError) throw error;
5271
+ const model = modelKeyOf(agent, named.model);
5272
+ const structured = settings.structured === "schema" && !refusesSchema.has(model);
5273
+ try {
5274
+ const ceiling = await outputCeiling(settings.maxTokens, agent, named.model, exec.signal);
5275
+ return await runChild({
5276
+ parent: agent,
5277
+ signal: exec.signal,
5278
+ persona: job.persona,
5279
+ prompt: job.prompt,
5280
+ result: job.result,
5281
+ ...job.check === void 0 ? {} : { beforeSubmit: (value) => job.check?.(value) },
5282
+ maxTokens: Math.min((job.maxTokens ?? ceiling) + ANALYSIS_TOKENS, ceiling),
5283
+ timeoutMinutes: settings.timeoutMinutes,
5284
+ ...named,
5285
+ ...structured ? { structured: true } : {},
5286
+ sampling: {
5287
+ temperature: settings.temperature,
5288
+ toolChoice: "required"
5289
+ },
5290
+ ...settings.reasoning === "" ? {} : { reasoningEffort: settings.reasoning }
5291
+ });
5292
+ } catch (error) {
5293
+ if (structured && !exec.signal.aborted && SCHEMA_REFUSED.test(error instanceof Error ? error.message : "")) {
5294
+ refusesSchema.add(model);
5295
+ attempt -= 1;
5296
+ continue;
5297
+ }
5298
+ if (exec.signal.aborted || attempt >= ATTEMPTS || error instanceof ChildTimeoutError) throw error;
5299
+ }
3324
5300
  }
3325
5301
  };
3326
5302
  const decide = settings.decisions === "decision" ? (state, asks) => {
@@ -3525,11 +5501,9 @@ function importHooks(ctx, worlds, prompting) {
3525
5501
  }));
3526
5502
  });
3527
5503
  }
3528
- //#endregion
3529
- //#region src/shared/import-selection.ts
5504
+ // src/shared/import-selection.ts
3530
5505
  const MAX_PREVIEW_TEXT = 4e3;
3531
- //#endregion
3532
- //#region src/host/tools/authoring-tools.ts
5506
+ // src/host/tools/authoring-tools.ts
3533
5507
  /** Which of the tools other plugins registered for everyone each assistant of the authoring chats was given in the settings; read afresh, so a change applies at its next step. */
3534
5508
  var AuthoringTools = class extends Service {
3535
5509
  board;
@@ -3568,7 +5542,6 @@ function limitAuthoringAgents(ctx, kindOf) {
3568
5542
  return await next();
3569
5543
  });
3570
5544
  }
3571
- //#endregion
3572
- export { knowsCharacter as $, alternateOpenings as A, loadCharacters as At, deleteLorebook as B, authoredWorldOf as Bt, addressKey as C, DICE_FILE_NAME as Ct, guardedLookup as D, loadCalendar as Dt, fetchPictures as E, CALENDAR_FILE_NAME as Et, WORLD_FILE_NAME as F, pictureOf as Ft, loadLorebook as G, entriesOf as H, parseWorldFile as I, readCard as It, reserveLorebook as J, lorebookDirectory as K, parseWorldInfoEdit as L, DICE_COMPARISONS as Lt, openingMessage as M, knownOutputCeiling as Mt, writePortrait as N, ImportCardError as Nt, mergeReports as O, parseCalendarFile as Ot, serialized as P, isPng as Pt, loadValidatedWorld as Q, addLorebookEntries as R, DICE_READINGS as Rt, CatalogueError as S, loadFactions as St, candidateUrls as T, parseDiceFile as Tt, isLorebookName as U, deleteLorebookEntry as V, authoringChatSessionId as Vt, listLorebooks as W, writeLorebookEntry as X, updateLorebookInfo as Y, checkWorld as Z, hashWorld as _, LOCATIONS_DIR as _t, importHooks as a, populateItems as at, readOrigin as b, loadItems as bt, importPhase as c, populateLore as ct, markReady as d, populateVariables as dt, populateCalendar as et, settleDraft as f, routineProblems as ft, describeChanges as g, loadLore as gt, writeSnapshot as h, LORE_DIR as ht, contextOf as i, populateFactions as it, cardCharacter as j, subfolders as jt, vetUrl as k, CHARACTERS_DIR as kt, isReviewing as l, populateRoutines as lt, editsSince as m, loadTriggers as mt, limitAuthoringAgents as n, populateClock as nt, importTools as o, populateKnowledge as ot, recordProvenance as p, TRIGGERS_FILE_NAME as pt, readLorebook as q, MAX_PREVIEW_TEXT as r, populateDice as rt, worldOf as s, populateLocations as st, AuthoringTools as t, populateCharacters as tt, keepDraft as u, populateTriggers as ut, isUnchanged as v, loadLocations as vt, addressesToFetch as w, loadDice as wt, writeOrigin as x, FACTIONS_DIR as xt, localChanges as y, ITEMS_DIR as yt, createLorebook as z, DICE_RESULTS as zt };
5545
+ export { WORLD_FILE_NAME as $, pictureOf as $t, cardTools as A, routineProblems as At, localChanges as B, loadFactions as Bt, worldFieldChanges as C, populateItems as Ct, UPDATE_FOLDER as D, populateRoutines as Dt, loadCardEvidence as E, populateLore as Et, editsSince as F, LOCATIONS_DIR as Ft, addressesToFetch as G, loadCalendar as Gt, writeOrigin as H, loadDice as Ht, writeSnapshot as I, loadLocations as It, guardedLookup as J, loadCharacters as Jt, candidateUrls as K, parseCalendarFile as Kt, describeChanges as L, ITEMS_DIR as Lt, readSource as M, loadTriggers as Mt, CHECK_COMMANDS as N, LORE_DIR as Nt, baseId as O, populateTriggers as Ot, recordProvenance as P, loadLore as Pt, writePortrait as Q, isPng as Qt, hashWorld as R, loadItems as Rt, matchPieces as S, populateFactions as St, loadWorldParts as T, populateLocations as Tt, CatalogueError as U, parseDiceFile as Ut, readOrigin as V, DICE_FILE_NAME as Vt, addressKey as W, CALENDAR_FILE_NAME as Wt, vetUrl as X, knownOutputCeiling as Xt, mergeReports as Y, subfolders as Yt, cardCharacter as Z, ImportCardError as Zt, runChecks as _, knowsCharacter as _t, importHooks as a, authoringChatSessionId as an, deleteLorebookEntry as at, cardChanges as b, populateClock as bt, importPhase as c, listLorebooks as ct, markReady as d, readLorebook as dt, readCard as en, parseWorldFile as et, settleDraft as f, reserveLorebook as ft, CHECKS as g, loadValidatedWorld as gt, presentReport as h, checkWorld as ht, contextOf as i, authoredWorldOf as in, deleteLorebook as it, entitiesByPiece as j, TRIGGERS_FILE_NAME as jt, cardPieces as k, populateVariables as kt, isReviewing as l, loadLorebook as lt, checkImported as m, writeLorebookEntry as mt, limitAuthoringAgents as n, DICE_READINGS as nn, addLorebookEntries as nt, importTools as o, entriesOf as ot, structureImport as p, updateLorebookInfo as pt, fetchPictures as q, CHARACTERS_DIR as qt, MAX_PREVIEW_TEXT as r, DICE_RESULTS as rn, createLorebook as rt, worldOf as s, isLorebookName as st, AuthoringTools as t, DICE_COMPARISONS as tn, parseWorldInfoEdit as tt, keepDraft as u, lorebookDirectory as ut, editWorldInfo as v, populateCalendar as vt, withScratchStory as w, populateKnowledge as wt, diffText as x, populateDice as xt, readWorldInfo as y, populateCharacters as yt, isUnchanged as z, FACTIONS_DIR as zt };
3573
5546
 
3574
- //# sourceMappingURL=authoring-tools-DNnx0Nts.js.map
5547
+ //# sourceMappingURL=authoring-tools-CdHlvx32.js.map