@dsh-agentic-roleplay/core 0.8.2 → 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 (40) hide show
  1. package/lib/{authoring-tools-BgmC2oqU.js → authoring-tools-CdHlvx32.js} +1909 -53
  2. package/lib/authoring.js +135 -32
  3. package/lib/client.js +347 -347
  4. package/lib/doctor.js +1 -1
  5. package/lib/{gallery-D1V4h8vh.js → gallery-BKh7eu80.js} +2 -2
  6. package/lib/{generator-CLPosooC.js → generator-DdZ1-sgv.js} +2 -2
  7. package/lib/{hooks-rQTTeOC4.js → hooks-CcQj_dJo.js} +2 -2
  8. package/lib/images.js +4 -4
  9. package/lib/index.js +14 -14
  10. package/lib/{library-Dfu0dgRj.js → library-QFL6Z_Nr.js} +2 -2
  11. package/lib/{lorebook-author-tools-BAaAqZZm.js → lorebook-author-tools-DWBnYo1E.js} +6 -6
  12. package/lib/lorebook-authoring.js +4 -4
  13. package/lib/orchestration.js +8 -8
  14. package/lib/{pack-jail-CN-314ln.js → pack-jail-BMy6NcCY.js} +21 -723
  15. package/lib/{packs-DIj5BEfq.js → packs-BREPSfHy.js} +2 -2
  16. package/lib/{presenter-agent-DR0KvLE0.js → presenter-agent-B49-_iUm.js} +4 -4
  17. package/lib/{preset-CscHj1-Y.js → preset-BqgY1Tz4.js} +3 -3
  18. package/lib/{preset-author-tools-CxluF8qc.js → preset-author-tools-BB_Dcv2o.js} +6 -6
  19. package/lib/preset-authoring.js +5 -5
  20. package/lib/{presets-HB8kJTaE.js → presets-Bwnrx7p0.js} +22 -11
  21. package/lib/{reflection-Dg1xtOTW.js → reflection-CUWG-6Qg.js} +6 -6
  22. package/lib/{text-DyRN4nDP.js → text-CbGQhK1-.js} +4 -3
  23. package/lib/{turn-guard-g_hDn0jR.js → turn-guard-Bb8Ew-1z.js} +2 -2
  24. package/package.json +2 -2
  25. package/prompts/en/checks/decide-sheet.md +1 -0
  26. package/prompts/en/checks/fidelity.md +7 -0
  27. package/prompts/en/checks/gaps.md +4 -0
  28. package/prompts/en/checks/notice.md +3 -0
  29. package/prompts/en/import/finish-draft.md +1 -1
  30. package/prompts/en/import/finish-ok.md +3 -1
  31. package/prompts/en/import/notice-repair.md +2 -2
  32. package/prompts/en/import/repair-again.md +2 -2
  33. package/prompts/zh/checks/decide-sheet.md +1 -0
  34. package/prompts/zh/checks/fidelity.md +7 -0
  35. package/prompts/zh/checks/gaps.md +4 -0
  36. package/prompts/zh/checks/notice.md +3 -0
  37. package/prompts/zh/import/finish-draft.md +1 -1
  38. package/prompts/zh/import/finish-ok.md +3 -1
  39. package/prompts/zh/import/notice-repair.md +2 -2
  40. package/prompts/zh/import/repair-again.md +2 -2
@@ -1,23 +1,24 @@
1
1
  import "./access-CfQWbNZP.js";
2
- import { C as inert, Ct as parseCharacterFile, D as pruneLoreSubjects, E as pruneLinks, Et as InvalidEditProblems, F as isLeftOut, Ft as WEEKDAY_NAMES, It as DEFAULT_SLOTS, J as cleanText, L as askYesNo, M as classifyItems, Nt as LORE_KINDS, O as pruneMembers, P as ROLES, Pt as LORE_SCOPES, Q as IMPORT_FOLDER, S as extractVariables, St as CHARACTER_FILE_NAME, T as pruneKnowledge, Tt as readIdentifier, Y as itemise, Z as withPlayer, _ as characterDocument, _t as SLOTS_FILE_NAME, a as isPresetName, b as extractStyle, bt as FACTION_FILE_NAME, ct as VARIABLES_FILE_NAME, dt as variableProblems, ft as LORE_FILE_NAME, g as asWritten, gt as ITEM_FILE_NAME, h as addLore, ht as parseLocationFile, it as readImportFolder, j as buildRoster, k as pruneRelationships, lt as loadVariables, mt as LOCATION_FILE_NAME, nt as openingText, pt as parseLoreFile, st as parseImportCommand, tt as PICTURE_FILE, v as emptyExtracted, vt as parseItemFile, w as loreDocuments, wt as readVariableValues, xt as parseFactionFile, y as extractEntities, yt as parseSlotsFile } from "./presets-HB8kJTaE.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
3
  import { l as atomicWrite, m as parseSwitchboard, u as atomicWriteJson } from "./narration-CjB_KwwY.js";
4
- import { B as loadPlots, H as plotReferenceProblems, K as readDocument, W as commandFlagKey, Y as errorMessage, Z as PROMPTS_FOLDER, a as externalWithheld, ht as COMPARISONS, it as shippedLanguages, lt as InvalidWorldError, ot as shippedText, q as Reader, r as externalGiven, rt as promptProblem, t as externalToolLimit } from "./hooks-rQTTeOC4.js";
5
- import { t as trimCharacters } from "./text-DyRN4nDP.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
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-Dfu0dgRj.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
+ import { tmpdir } from "node:os";
21
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. */
@@ -90,7 +91,7 @@ function chunksOf(file) {
90
91
  return chunks;
91
92
  }
92
93
  /** The keyword and text of a PNG text chunk. */
93
- function textOf(chunk) {
94
+ function textOf$1(chunk) {
94
95
  const end = chunk.data.indexOf(0);
95
96
  if (end < 0) return void 0;
96
97
  const keyword = chunk.data.toString("latin1", 0, end);
@@ -122,7 +123,7 @@ function jsonOf(file, name) {
122
123
  const found = /* @__PURE__ */ new Map();
123
124
  for (const chunk of chunksOf(file)) {
124
125
  if (!TEXT_CHUNKS.has(chunk.type)) continue;
125
- const text = textOf(chunk);
126
+ const text = textOf$1(chunk);
126
127
  if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
127
128
  }
128
129
  const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
@@ -156,7 +157,7 @@ function urlsOf(value) {
156
157
  return [...found];
157
158
  }
158
159
  const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
159
- 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) : "";
160
161
  const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
161
162
  function entryOf(value, index) {
162
163
  const entry = object(value);
@@ -164,10 +165,10 @@ function entryOf(value, index) {
164
165
  const position = entry["position"];
165
166
  return {
166
167
  id: `entry:${index}`,
167
- title: text(entry["comment"]).trim() || text(entry["name"]).trim(),
168
+ title: text$1(entry["comment"]).trim() || text$1(entry["name"]).trim(),
168
169
  keys: texts(entry["keys"]),
169
170
  secondaryKeys: texts(entry["secondary_keys"]),
170
- content: text(entry["content"]),
171
+ content: text$1(entry["content"]),
171
172
  enabled: entry["enabled"] !== false,
172
173
  constant: entry["constant"] === true,
173
174
  selective: entry["selective"] === true,
@@ -182,10 +183,10 @@ function entryOf(value, index) {
182
183
  function readCard(file, name) {
183
184
  const root = object(jsonOf(file, name));
184
185
  const spec = root === void 0 ? void 0 : root["spec"];
185
- 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`);
186
187
  const data = object(root?.["data"]);
187
188
  if (data === void 0) throw new ImportCardError(`${name} has no card data`);
188
- const cardName = text(data["name"]).trim();
189
+ const cardName = text$1(data["name"]).trim();
189
190
  if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
190
191
  const book = object(data["character_book"]);
191
192
  const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
@@ -194,21 +195,21 @@ function readCard(file, name) {
194
195
  return {
195
196
  sourceSpec: spec,
196
197
  name: cardName,
197
- description: text(data["description"]),
198
- personality: text(data["personality"]),
199
- scenario: text(data["scenario"]),
200
- 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"]),
201
202
  alternateGreetings: texts(data["alternate_greetings"]),
202
- messageExample: text(data["mes_example"]),
203
- creatorNotes: text(data["creator_notes"]),
204
- systemPrompt: text(data["system_prompt"]),
205
- 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"]),
206
207
  tags: texts(data["tags"]),
207
- creator: text(data["creator"]),
208
- characterVersion: text(data["character_version"]),
208
+ creator: text$1(data["creator"]),
209
+ characterVersion: text$1(data["character_version"]),
209
210
  ...book === void 0 ? {} : { book: {
210
- name: text(book["name"]),
211
- description: text(book["description"]),
211
+ name: text$1(book["name"]),
212
+ description: text$1(book["description"]),
212
213
  entries
213
214
  } },
214
215
  ignored: {
@@ -301,7 +302,7 @@ async function loadCharacters(worldDir) {
301
302
  for (const folder of folders) {
302
303
  const file = join(dir, folder, CHARACTER_FILE_NAME);
303
304
  try {
304
- const character = await readDocument(file, (text) => parseCharacterFile(text, folder), result.problems);
305
+ const character = await readDocument$1(file, (text) => parseCharacterFile(text, folder), result.problems);
305
306
  if (character === void 0) continue;
306
307
  const owner = folderById.get(character.id);
307
308
  if (owner !== void 0) {
@@ -376,7 +377,7 @@ async function loadCalendar(worldDir) {
376
377
  };
377
378
  const file = join(worldDir, CALENDAR_FILE_NAME);
378
379
  try {
379
- result.calendar = await readDocument(file, parseCalendarFile, result.problems) ?? result.calendar;
380
+ result.calendar = await readDocument$1(file, parseCalendarFile, result.problems) ?? result.calendar;
380
381
  } catch (error) {
381
382
  if (error.code !== "ENOENT") result.problems.push({
382
383
  path: file,
@@ -449,7 +450,7 @@ async function loadCommands(worldDir) {
449
450
  };
450
451
  const file = join(worldDir, COMMANDS_FILE_NAME);
451
452
  try {
452
- result.commands = await readDocument(file, parseCommandsFile, result.problems) ?? [];
453
+ result.commands = await readDocument$1(file, parseCommandsFile, result.problems) ?? [];
453
454
  } catch (error) {
454
455
  if (error.code !== "ENOENT") result.problems.push({
455
456
  path: file,
@@ -537,7 +538,7 @@ async function loadDice(worldDir) {
537
538
  };
538
539
  const file = join(worldDir, DICE_FILE_NAME);
539
540
  try {
540
- result.checks = await readDocument(file, parseDiceFile, result.problems) ?? [];
541
+ result.checks = await readDocument$1(file, parseDiceFile, result.problems) ?? [];
541
542
  } catch (error) {
542
543
  if (error.code !== "ENOENT") result.problems.push({
543
544
  path: file,
@@ -568,7 +569,7 @@ async function loadFactions(worldDir) {
568
569
  for (const folder of folders) {
569
570
  const file = join(dir, folder, FACTION_FILE_NAME);
570
571
  try {
571
- const faction = await readDocument(file, (text) => parseFactionFile(text, folder), result.problems);
572
+ const faction = await readDocument$1(file, (text) => parseFactionFile(text, folder), result.problems);
572
573
  if (faction === void 0) continue;
573
574
  const owner = owners.get(faction.id);
574
575
  if (owner !== void 0) {
@@ -621,7 +622,7 @@ async function loadItems(worldDir, context) {
621
622
  return result;
622
623
  }
623
624
  try {
624
- 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);
625
626
  for (const slot of own ?? []) {
626
627
  const at = result.slots.findIndex((existing) => existing.id === slot.id);
627
628
  if (at < 0) result.slots.push(slot);
@@ -637,7 +638,7 @@ async function loadItems(worldDir, context) {
637
638
  for (const folder of folders) {
638
639
  const file = join(dir, folder, ITEM_FILE_NAME);
639
640
  try {
640
- const item = await readDocument(file, (text) => parseItemFile(text, folder), result.problems);
641
+ const item = await readDocument$1(file, (text) => parseItemFile(text, folder), result.problems);
641
642
  if (item === void 0) continue;
642
643
  const owner = folderOf.get(item.id);
643
644
  if (owner !== void 0) {
@@ -747,7 +748,7 @@ async function loadLocations(worldDir) {
747
748
  for (const folder of folders) {
748
749
  const file = join(dir, folder, LOCATION_FILE_NAME);
749
750
  try {
750
- const location = await readDocument(file, (text) => parseLocationFile(text, folder), result.problems);
751
+ const location = await readDocument$1(file, (text) => parseLocationFile(text, folder), result.problems);
751
752
  if (location === void 0) continue;
752
753
  const owner = files.get(location.id);
753
754
  if (owner !== void 0) {
@@ -842,7 +843,7 @@ async function loadLore(worldDir) {
842
843
  for (const folder of folders) {
843
844
  const file = join(dir, folder, LORE_FILE_NAME);
844
845
  try {
845
- const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
846
+ const entry = await readDocument$1(file, (text) => parseLoreFile(text, folder), result.problems);
846
847
  if (entry === void 0) continue;
847
848
  const owner = owners.get(entry.id);
848
849
  if (owner !== void 0) {
@@ -926,7 +927,7 @@ async function loadTriggers(worldDir) {
926
927
  };
927
928
  const file = join(worldDir, TRIGGERS_FILE_NAME);
928
929
  try {
929
- result.triggers = await readDocument(file, parseTriggersFile, result.problems) ?? [];
930
+ result.triggers = await readDocument$1(file, parseTriggersFile, result.problems) ?? [];
930
931
  } catch (error) {
931
932
  if (error.code !== "ENOENT") result.problems.push({
932
933
  path: file,
@@ -1424,7 +1425,7 @@ async function loadValidatedWorld(world) {
1424
1425
  }
1425
1426
  // src/host/worlds/world-check.ts
1426
1427
  /** The most problems listed at once: the rest are named by their number. */
1427
- const LISTED = 40;
1428
+ const LISTED$1 = 40;
1428
1429
  /**
1429
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
1430
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
@@ -1447,8 +1448,8 @@ async function checkWorld(world) {
1447
1448
  return {
1448
1449
  ok: false,
1449
1450
  summary: error.message,
1450
- problems: problems.slice(0, LISTED),
1451
- more: Math.max(0, problems.length - LISTED)
1451
+ problems: problems.slice(0, LISTED$1),
1452
+ more: Math.max(0, problems.length - LISTED$1)
1452
1453
  };
1453
1454
  }
1454
1455
  }
@@ -2181,12 +2182,9 @@ function updateWorldFile(directory, update) {
2181
2182
  return document;
2182
2183
  });
2183
2184
  }
2184
- // src/host/import/finish.ts
2185
- const STAGE = "stage";
2186
- const MAX_DESCRIPTION = 500;
2187
- const MAX_TAGS = 8;
2188
- const MAX_TAG = 30;
2189
- 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 = [
2190
2188
  {
2191
2189
  key: "characters",
2192
2190
  directory: CHARACTERS_DIR,
@@ -2213,6 +2211,11 @@ const FOLDERS = [
2213
2211
  file: LORE_FILE_NAME
2214
2212
  }
2215
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;
2216
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. */
2217
2220
  function alternateOpenings(card, chosen, player) {
2218
2221
  if (chosen.kind === "none") return [];
@@ -2400,7 +2403,7 @@ async function describeWorld(ctx, card, roster, items, opening) {
2400
2403
  }
2401
2404
  }
2402
2405
  async function hasEntities(world) {
2403
- for (const { directory } of FOLDERS) try {
2406
+ for (const { directory } of ENTITY_FOLDERS) try {
2404
2407
  if ((await readdir(join(world, directory))).some((name) => !name.startsWith("."))) return true;
2405
2408
  } catch (error) {
2406
2409
  if (error.code !== "ENOENT") throw error;
@@ -2457,7 +2460,7 @@ async function finishImport(ctx, input) {
2457
2460
  if (extracted.variables.length > 0) await writeAtomically(join(stage, VARIABLES_FILE_NAME), `${JSON.stringify(extracted.variables, null, 2)}\n`);
2458
2461
  if (extracted.commands.length > 0) await writeAtomically(join(stage, COMMANDS_FILE_NAME), `${JSON.stringify({ commands: extracted.commands }, null, 2)}\n`);
2459
2462
  if (extracted.triggers.length > 0) await writeAtomically(join(stage, TRIGGERS_FILE_NAME), `${JSON.stringify(extracted.triggers, null, 2)}\n`);
2460
- 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`);
2461
2464
  for (const { id, text } of extracted.prompts) {
2462
2465
  const problem = promptProblem("en", id, text);
2463
2466
  if (problem !== void 0) return {
@@ -2468,7 +2471,7 @@ async function finishImport(ctx, input) {
2468
2471
  if (extracted.variables.length > 0) await rename(join(stage, VARIABLES_FILE_NAME), join(directory, VARIABLES_FILE_NAME));
2469
2472
  if (extracted.commands.length > 0) await rename(join(stage, COMMANDS_FILE_NAME), join(directory, COMMANDS_FILE_NAME));
2470
2473
  if (extracted.triggers.length > 0) await rename(join(stage, TRIGGERS_FILE_NAME), join(directory, TRIGGERS_FILE_NAME));
2471
- for (const { directory: folder } of FOLDERS) {
2474
+ for (const { directory: folder } of ENTITY_FOLDERS) {
2472
2475
  const from = join(stage, folder);
2473
2476
  if (await stat(from).then(() => true, () => false)) await rename(from, join(directory, folder));
2474
2477
  }
@@ -3043,19 +3046,19 @@ async function editsSince(directory) {
3043
3046
  };
3044
3047
  }
3045
3048
  // src/host/import/provenance.ts
3046
- const FILE = "provenance.json";
3049
+ const FILE$1 = "provenance.json";
3047
3050
  const PROVENANCE_SCHEMA = "dsh-roleplay-import/v1";
3048
3051
  /** The import record of a world, or nothing for a world imported before records were kept. */
3049
3052
  async function readProvenance(directory) {
3050
3053
  let text;
3051
3054
  try {
3052
- text = await readFile(join(directory, IMPORT_FOLDER, FILE), "utf8");
3055
+ text = await readFile(join(directory, IMPORT_FOLDER, FILE$1), "utf8");
3053
3056
  } catch (error) {
3054
3057
  if (error.code === "ENOENT") return void 0;
3055
3058
  throw error;
3056
3059
  }
3057
3060
  const value = JSON.parse(text);
3058
- 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`);
3059
3062
  return value;
3060
3063
  }
3061
3064
  /** Adds one line to the world's import record: what card it came from and, for an import, what was written. */
@@ -3069,11 +3072,1859 @@ async function recordProvenance(directory, entry, cardJson) {
3069
3072
  sha256: createHash("sha256").update(cardJson).digest("hex")
3070
3073
  }
3071
3074
  };
3072
- await atomicWriteJson(join(directory, IMPORT_FOLDER, FILE), {
3075
+ await atomicWriteJson(join(directory, IMPORT_FOLDER, FILE$1), {
3073
3076
  schema: PROVENANCE_SCHEMA,
3074
3077
  history: [...earlier?.history ?? [], line]
3075
3078
  });
3076
3079
  }
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
+ }
3077
4928
  // src/host/import/run-import.ts
3078
4929
  /** The import in a world is not in the state the step needs, or there is none. The message says what to do. */
3079
4930
  var ImportStateError = class extends Error {};
@@ -3311,6 +5162,10 @@ async function finish(ctx, world) {
3311
5162
  counts: result.report.counts,
3312
5163
  notes: result.report.notes.length
3313
5164
  }, await readFile(join(folder(world), "card.json"), "utf8"));
5165
+ return {
5166
+ ...result,
5167
+ checks: await checkImported(world, choices.name)
5168
+ };
3314
5169
  }
3315
5170
  return result;
3316
5171
  }
@@ -3355,6 +5210,7 @@ async function structureImport(world, language) {
3355
5210
  counts: result.report.counts,
3356
5211
  notes: result.report.notes.length
3357
5212
  }, await readFile(join(folder(world), "card.json"), "utf8"));
5213
+ await checkImported(world, choices.name);
3358
5214
  return {
3359
5215
  report: result.report,
3360
5216
  ...result.draft === void 0 ? {} : { draft: result.draft }
@@ -3686,6 +5542,6 @@ function limitAuthoringAgents(ctx, kindOf) {
3686
5542
  return await next();
3687
5543
  });
3688
5544
  }
3689
- export { loadValidatedWorld as $, vetUrl as A, CHARACTERS_DIR as At, createLorebook as B, DICE_RESULTS as Bt, CatalogueError as C, loadFactions as Ct, fetchPictures as D, CALENDAR_FILE_NAME as Dt, candidateUrls as E, parseDiceFile as Et, serialized as F, isPng as Ft, listLorebooks as G, deleteLorebookEntry as H, authoringChatSessionId as Ht, WORLD_FILE_NAME as I, pictureOf as It, readLorebook as J, loadLorebook as K, parseWorldFile as L, readCard as Lt, cardCharacter as M, subfolders as Mt, openingMessage as N, knownOutputCeiling as Nt, guardedLookup as O, loadCalendar as Ot, writePortrait as P, ImportCardError as Pt, checkWorld as Q, parseWorldInfoEdit as R, DICE_COMPARISONS as Rt, writeOrigin as S, FACTIONS_DIR as St, addressesToFetch as T, loadDice as Tt, entriesOf as U, deleteLorebook as V, authoredWorldOf as Vt, isLorebookName as W, updateLorebookInfo as X, reserveLorebook as Y, writeLorebookEntry as Z, describeChanges as _, loadLore as _t, importHooks as a, populateFactions as at, localChanges as b, ITEMS_DIR as bt, importPhase as c, populateLocations as ct, markReady as d, populateTriggers as dt, knowsCharacter as et, settleDraft as f, populateVariables as ft, writeSnapshot as g, LORE_DIR as gt, editsSince as h, loadTriggers as ht, contextOf as i, populateDice as it, alternateOpenings as j, loadCharacters as jt, mergeReports as k, parseCalendarFile as kt, isReviewing as l, populateLore as lt, recordProvenance as m, TRIGGERS_FILE_NAME as mt, limitAuthoringAgents as n, populateCharacters as nt, importTools as o, populateItems as ot, structureImport as p, routineProblems as pt, lorebookDirectory as q, MAX_PREVIEW_TEXT as r, populateClock as rt, worldOf as s, populateKnowledge as st, AuthoringTools as t, populateCalendar as tt, keepDraft as u, populateRoutines as ut, hashWorld as v, LOCATIONS_DIR as vt, addressKey as w, DICE_FILE_NAME as wt, readOrigin as x, loadItems as xt, isUnchanged as y, loadLocations as yt, addLorebookEntries as z, DICE_READINGS 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 };
3690
5546
 
3691
- //# sourceMappingURL=authoring-tools-BgmC2oqU.js.map
5547
+ //# sourceMappingURL=authoring-tools-CdHlvx32.js.map