@dsh-agentic-roleplay/core 0.8.2 → 0.9.1

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 (52) hide show
  1. package/lib/{authoring-tools-BgmC2oqU.js → authoring-tools-C_l07RYn.js} +2568 -53
  2. package/lib/authoring.js +145 -38
  3. package/lib/client.js +327 -327
  4. package/lib/doctor.js +1 -1
  5. package/lib/{gallery-D1V4h8vh.js → gallery-q7niLtWn.js} +2 -2
  6. package/lib/{generator-CLPosooC.js → generator-BpjPrvHe.js} +2 -2
  7. package/lib/{hooks-rQTTeOC4.js → hooks-DNaDzMjW.js} +38 -5
  8. package/lib/images.js +4 -4
  9. package/lib/index.js +14 -14
  10. package/lib/{library-Dfu0dgRj.js → library-CIkxhf_R.js} +5 -3
  11. package/lib/{lorebook-author-tools-BAaAqZZm.js → lorebook-author-tools-BiMDmdFi.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-B35Vx3hT.js} +36 -728
  15. package/lib/{packs-DIj5BEfq.js → packs-BajKw7S9.js} +2 -2
  16. package/lib/{presenter-agent-DR0KvLE0.js → presenter-agent-jgtuTwZr.js} +4 -4
  17. package/lib/{preset-CscHj1-Y.js → preset-DWgkcPau.js} +3 -3
  18. package/lib/{preset-author-tools-CxluF8qc.js → preset-author-tools-BhuYIKms.js} +6 -6
  19. package/lib/preset-authoring.js +5 -5
  20. package/lib/{presets-HB8kJTaE.js → presets-9GzaSELc.js} +32 -12
  21. package/lib/{reflection-Dg1xtOTW.js → reflection-4L0Plvct.js} +6 -6
  22. package/lib/{text-DyRN4nDP.js → text-CbGQhK1-.js} +4 -3
  23. package/lib/{turn-guard-g_hDn0jR.js → turn-guard-sCUXmp-5.js} +2 -2
  24. package/package.json +2 -2
  25. package/prompts/en/checks/conflict.md +1 -0
  26. package/prompts/en/checks/decide-conflict.md +1 -0
  27. package/prompts/en/checks/decide-covered.md +1 -0
  28. package/prompts/en/checks/decide-opening.md +1 -0
  29. package/prompts/en/checks/decide-same-thing.md +1 -0
  30. package/prompts/en/checks/decide-same-value.md +1 -0
  31. package/prompts/en/checks/decide-sheet.md +1 -0
  32. package/prompts/en/checks/fidelity.md +7 -0
  33. package/prompts/en/checks/gaps.md +4 -0
  34. package/prompts/en/checks/notice.md +3 -0
  35. package/prompts/en/import/finish-draft.md +1 -1
  36. package/prompts/en/import/finish-ok.md +3 -1
  37. package/prompts/en/import/notice-repair.md +2 -2
  38. package/prompts/en/import/repair-again.md +2 -2
  39. package/prompts/zh/checks/conflict.md +1 -0
  40. package/prompts/zh/checks/decide-conflict.md +1 -0
  41. package/prompts/zh/checks/decide-covered.md +1 -0
  42. package/prompts/zh/checks/decide-opening.md +1 -0
  43. package/prompts/zh/checks/decide-same-thing.md +1 -0
  44. package/prompts/zh/checks/decide-same-value.md +1 -0
  45. package/prompts/zh/checks/decide-sheet.md +1 -0
  46. package/prompts/zh/checks/fidelity.md +7 -0
  47. package/prompts/zh/checks/gaps.md +4 -0
  48. package/prompts/zh/checks/notice.md +3 -0
  49. package/prompts/zh/import/finish-draft.md +1 -1
  50. package/prompts/zh/import/finish-ok.md +3 -1
  51. package/prompts/zh/import/notice-repair.md +2 -2
  52. 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-9GzaSELc.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-DNaDzMjW.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 slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-CIkxhf_R.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$2 = "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$2), "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$2} 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,2505 @@ 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$2), {
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
+ "playability"
3087
+ ];
3088
+ const SEVERITIES = [
3089
+ "error",
3090
+ "warning",
3091
+ "info"
3092
+ ];
3093
+ /** The commands of an authoring chat that start checks, and the kits each runs. */
3094
+ const CHECK_COMMANDS = {
3095
+ check: KITS,
3096
+ "check-all": KITS,
3097
+ "check-world": ["consistency"],
3098
+ "check-card": ["fidelity"],
3099
+ "check-quality": ["quality"],
3100
+ "check-play": ["playability"]
3101
+ };
3102
+ const findingKey = (finding) => `${finding.check}\n${finding.code}\n${finding.where}\n${finding.message}`;
3103
+ // src/host/import/card-tools.ts
3104
+ /** The most of a piece one `card_read` returns; a long lorebook entry is read in turns. */
3105
+ const READ_CHARS = 6e3;
3106
+ const SNIPPET_CHARS = 240;
3107
+ const DEFAULT_HITS = 8;
3108
+ const MAX_HITS = 20;
3109
+ const baseId = (id) => id.replace(/#\d+$/, "");
3110
+ /** The folder inside `.import` where a newer version of the card waits to be applied to the world. */
3111
+ const UPDATE_FOLDER = "update";
3112
+ /** Everything the card holds, in the order the card has it. */
3113
+ function cardPieces(card, choices) {
3114
+ const read = new Set(itemise(card, choices).map((item) => baseId(item.id)));
3115
+ const field = (id, label, text) => text.trim() === "" ? [] : [{
3116
+ id,
3117
+ label,
3118
+ title: "",
3119
+ keys: [],
3120
+ text,
3121
+ used: read.has(id)
3122
+ }];
3123
+ return [
3124
+ ...field("field:description", "description", card.description),
3125
+ ...field("field:personality", "personality", card.personality),
3126
+ ...field("field:scenario", "scenario", card.scenario),
3127
+ ...field("field:example", "example messages", card.messageExample),
3128
+ ...field("field:first-message", "first message", card.firstMessage),
3129
+ ...card.alternateGreetings.flatMap((text, index) => field(`field:greeting-${index + 1}`, `alternate greeting ${index + 1}`, text)),
3130
+ ...field("field:creator-notes", "creator's notes", card.creatorNotes),
3131
+ ...field("field:system-prompt", "system prompt", card.systemPrompt),
3132
+ ...field("field:post-history", "post-history instructions", card.postHistoryInstructions),
3133
+ ...(card.book?.entries ?? []).filter((entry) => entry.content.trim() !== "").map((entry) => ({
3134
+ id: entry.id,
3135
+ label: entry.title === "" ? entry.id : `entry “${entry.title}”`,
3136
+ title: entry.title,
3137
+ keys: entry.keys,
3138
+ text: entry.content,
3139
+ used: read.has(entry.id),
3140
+ enabled: entry.enabled
3141
+ }))
3142
+ ];
3143
+ }
3144
+ async function optional(file) {
3145
+ try {
3146
+ return JSON.parse(await readFile(file, "utf8"));
3147
+ } catch (error) {
3148
+ if (error.code === "ENOENT") return void 0;
3149
+ throw error;
3150
+ }
3151
+ }
3152
+ /** 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. */
3153
+ async function readSource(directory, withRecords, version = "current") {
3154
+ const folder = join(directory, IMPORT_FOLDER);
3155
+ let read;
3156
+ try {
3157
+ read = await readImportFolder(version === "new" ? join(folder, UPDATE_FOLDER) : folder);
3158
+ } catch (error) {
3159
+ 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");
3160
+ throw error;
3161
+ }
3162
+ const records = withRecords && version === "current" ? {
3163
+ classified: await optional(join(folder, "classification.json")),
3164
+ roster: await optional(join(folder, "roster.json")),
3165
+ report: await optional(join(folder, "report.json"))
3166
+ } : {};
3167
+ return {
3168
+ card: read.card,
3169
+ choices: read.choices,
3170
+ pieces: cardPieces(read.card, read.choices),
3171
+ records
3172
+ };
3173
+ }
3174
+ const rolesOf = (classified, id) => {
3175
+ if (classified === void 0) return [];
3176
+ return [...new Set(Object.entries(classified).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
3177
+ };
3178
+ function snippet$1(text, at, length) {
3179
+ const start = Math.max(0, at - Math.floor((SNIPPET_CHARS - length) / 2));
3180
+ const end = Math.min(text.length, start + SNIPPET_CHARS);
3181
+ return `${start > 0 ? "…" : ""}${text.slice(start, end).replace(/\s+/g, " ")}${end < text.length ? "…" : ""}`;
3182
+ }
3183
+ function searchPieces(pieces, query, limit) {
3184
+ const phrase = query.trim().toLowerCase();
3185
+ if (phrase === "") return [];
3186
+ const words = [...new Set(phrase.split(/[\s,;,、]+/).filter((word) => word.length >= (/^[\x00-\x7f]+$/.test(word) ? 3 : 2)))];
3187
+ const count = (text, needle) => {
3188
+ let n = 0;
3189
+ let first = -1;
3190
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
3191
+ n += 1;
3192
+ if (first < 0) first = at;
3193
+ }
3194
+ return {
3195
+ n,
3196
+ first
3197
+ };
3198
+ };
3199
+ const look = (text) => {
3200
+ const lowered = text.toLowerCase();
3201
+ const whole = count(lowered, phrase);
3202
+ if (whole.n > 0) return {
3203
+ matches: whole.n,
3204
+ score: whole.n * 4 + 100,
3205
+ at: whole.first,
3206
+ length: phrase.length
3207
+ };
3208
+ const found = words.map((word) => ({
3209
+ word,
3210
+ ...count(lowered, word)
3211
+ })).filter((entry) => entry.n > 0);
3212
+ if (found.length === 0) return void 0;
3213
+ const best = found.reduce((a, b) => a.first <= b.first ? a : b, found[0]);
3214
+ return {
3215
+ matches: found.reduce((sum, entry) => sum + entry.n, 0),
3216
+ score: found.length * 10 + found.reduce((sum, entry) => sum + entry.n, 0),
3217
+ at: best.first,
3218
+ length: best.word.length
3219
+ };
3220
+ };
3221
+ return pieces.flatMap((piece) => {
3222
+ const inText = look(piece.text);
3223
+ if (inText !== void 0) return [{
3224
+ piece,
3225
+ in: "text",
3226
+ matches: inText.matches,
3227
+ score: inText.score,
3228
+ snippet: snippet$1(piece.text, inText.at, inText.length)
3229
+ }];
3230
+ const head = [piece.title, ...piece.keys].filter((part) => part !== "").join(" · ");
3231
+ const inHead = look(head);
3232
+ return inHead === void 0 ? [] : [{
3233
+ piece,
3234
+ in: "title or keys",
3235
+ matches: inHead.matches,
3236
+ score: inHead.score - 50,
3237
+ snippet: `${piece.title === "" ? "" : `title: ${piece.title}`}${piece.keys.length === 0 ? "" : `${piece.title === "" ? "" : "; "}keys: ${piece.keys.join(", ")}`}`
3238
+ }];
3239
+ }).sort((a, b) => b.score - a.score).slice(0, limit).map(({ piece, matches, in: where, snippet: text }) => ({
3240
+ piece,
3241
+ matches,
3242
+ in: where,
3243
+ snippet: text
3244
+ }));
3245
+ }
3246
+ const versionParameter = {
3247
+ type: "string",
3248
+ enum: ["current", "new"],
3249
+ 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."
3250
+ };
3251
+ const output$1 = {
3252
+ schema: { type: "json" },
3253
+ render: (_args, value) => [{
3254
+ type: "text",
3255
+ text: JSON.stringify(value, null, 1)
3256
+ }]
3257
+ };
3258
+ const json$1 = (value) => JSON.parse(JSON.stringify(value));
3259
+ const idOf = (exec) => {
3260
+ const chat = exec.agent?.session.id;
3261
+ const world = chat === void 0 ? void 0 : authoredWorldOf(chat);
3262
+ if (world === void 0) throw new Error("this tool is available only in a world authoring chat");
3263
+ return world;
3264
+ };
3265
+ /**
3266
+ * 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.
3267
+ * `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.
3268
+ */
3269
+ function cardTools(worlds, options = {}) {
3270
+ const withRecords = options.records !== false;
3271
+ const source = async (exec, version = "current") => {
3272
+ const id = idOf(exec);
3273
+ const record = await worlds.find(id);
3274
+ if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
3275
+ return await readSource(record.directory, withRecords, version);
3276
+ };
3277
+ const versionOf = (value) => {
3278
+ if (value === void 0 || value === "current") return "current";
3279
+ if (value === "new") return "new";
3280
+ throw new Error("version must be current or new");
3281
+ };
3282
+ const find = (pieces, id) => {
3283
+ const found = pieces.find((piece) => piece.id === id);
3284
+ if (found === void 0) throw new Error(`the card has no piece "${id}": use an id from card_overview or card_search`);
3285
+ return found;
3286
+ };
3287
+ return [
3288
+ defineTool({
3289
+ name: "card_overview",
3290
+ 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.",
3291
+ parameters: {},
3292
+ output: output$1,
3293
+ isConcurrencySafe: () => true,
3294
+ async execute(_args, exec) {
3295
+ const { card, choices, pieces, records } = await source(exec);
3296
+ const madeFrom = entitiesByPiece({
3297
+ card,
3298
+ choices,
3299
+ pieces,
3300
+ records
3301
+ });
3302
+ const made = (id) => madeFrom.get(id) ?? [];
3303
+ return json$1({
3304
+ card: {
3305
+ name: card.name,
3306
+ creator: card.creator,
3307
+ version: card.characterVersion,
3308
+ tags: card.tags,
3309
+ format: card.sourceSpec,
3310
+ ignoredScripts: card.ignored.scripts
3311
+ },
3312
+ pieces: pieces.map((piece) => ({
3313
+ id: piece.id,
3314
+ label: piece.label,
3315
+ characters: piece.text.length,
3316
+ readByTheImport: piece.used,
3317
+ ...piece.enabled === void 0 ? {} : { switchedOnInCard: piece.enabled },
3318
+ ...withRecords ? {
3319
+ takenToBe: rolesOf(records.classified, piece.id),
3320
+ madeInto: made(piece.id)
3321
+ } : {}
3322
+ })),
3323
+ ...records.roster === void 0 ? {} : { imported: records.roster.map((entity) => ({
3324
+ name: entity.name,
3325
+ kind: entity.kind,
3326
+ aliases: entity.aliases,
3327
+ playedByThePlayer: entity.player
3328
+ })) },
3329
+ ...records.report === void 0 ? {} : {
3330
+ importNotes: records.report.notes,
3331
+ leftOut: records.report.leftOut
3332
+ },
3333
+ 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."
3334
+ });
3335
+ }
3336
+ }),
3337
+ defineTool({
3338
+ name: "card_search",
3339
+ 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.",
3340
+ parameters: {
3341
+ query: {
3342
+ type: "string",
3343
+ required: true,
3344
+ description: "A name or phrase to look for, in the card's own language."
3345
+ },
3346
+ version: versionParameter,
3347
+ limit: {
3348
+ type: "number",
3349
+ description: `How many pieces to return, at most ${MAX_HITS} (default ${DEFAULT_HITS}).`
3350
+ }
3351
+ },
3352
+ output: output$1,
3353
+ isConcurrencySafe: () => true,
3354
+ async execute(args, exec) {
3355
+ const { pieces } = await source(exec, versionOf(args.version));
3356
+ const limit = Math.min(MAX_HITS, Math.max(1, Math.floor(typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : DEFAULT_HITS)));
3357
+ const hits = searchPieces(pieces, args.query, limit);
3358
+ return json$1({
3359
+ query: args.query,
3360
+ found: hits.length,
3361
+ hits: hits.map(({ piece, matches, in: where, snippet: text }) => ({
3362
+ piece: piece.id,
3363
+ label: piece.label,
3364
+ matches,
3365
+ foundIn: where,
3366
+ snippet: text
3367
+ }))
3368
+ });
3369
+ }
3370
+ }),
3371
+ defineTool({
3372
+ name: "card_read",
3373
+ 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.`,
3374
+ parameters: {
3375
+ piece: {
3376
+ type: "string",
3377
+ required: true,
3378
+ description: "A piece id from card_overview, card_search or card_diff, such as field:description or entry:3."
3379
+ },
3380
+ version: versionParameter,
3381
+ offset: {
3382
+ type: "number",
3383
+ description: "Where to start reading, in characters (default 0)."
3384
+ }
3385
+ },
3386
+ output: output$1,
3387
+ isConcurrencySafe: () => true,
3388
+ async execute(args, exec) {
3389
+ const { pieces } = await source(exec, versionOf(args.version));
3390
+ const piece = find(pieces, args.piece);
3391
+ const from = Math.min(piece.text.length, Math.max(0, Math.floor(typeof args.offset === "number" && Number.isFinite(args.offset) ? args.offset : 0)));
3392
+ const to = Math.min(piece.text.length, from + READ_CHARS);
3393
+ return json$1({
3394
+ piece: piece.id,
3395
+ label: piece.label,
3396
+ ...piece.keys.length === 0 ? {} : { keys: piece.keys },
3397
+ from,
3398
+ to,
3399
+ of: piece.text.length,
3400
+ ...to < piece.text.length ? { next: to } : {},
3401
+ text: piece.text.slice(from, to)
3402
+ });
3403
+ }
3404
+ }),
3405
+ defineTool({
3406
+ name: "card_origin",
3407
+ 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.",
3408
+ parameters: { name: {
3409
+ type: "string",
3410
+ required: true,
3411
+ description: "The name or an alias, as the world or the card has it."
3412
+ } },
3413
+ output: output$1,
3414
+ isConcurrencySafe: () => true,
3415
+ async execute(args, exec) {
3416
+ const { card, choices, pieces, records } = await source(exec);
3417
+ const entity = records.roster === void 0 ? void 0 : findEntity(records.roster, args.name);
3418
+ if (entity === void 0 || records.classified === void 0) return json$1({
3419
+ name: args.name,
3420
+ madeByTheImport: false,
3421
+ mentions: searchPieces(pieces, args.name, DEFAULT_HITS).map(({ piece, in: where, snippet: text }) => ({
3422
+ piece: piece.id,
3423
+ label: piece.label,
3424
+ foundIn: where,
3425
+ snippet: text
3426
+ }))
3427
+ });
3428
+ return json$1({
3429
+ name: entity.name,
3430
+ kind: entity.kind,
3431
+ aliases: entity.aliases,
3432
+ madeByTheImport: true,
3433
+ usedPieces: originOf(card, choices, pieces, records, entity.name).map((entry) => ({
3434
+ piece: entry.piece,
3435
+ label: entry.label,
3436
+ how: entry.how,
3437
+ takenToBe: rolesOf(records.classified, entry.piece)
3438
+ }))
3439
+ });
3440
+ }
3441
+ })
3442
+ ];
3443
+ }
3444
+ /** For each piece of the card, the names of the characters, places and things the import made from it. */
3445
+ function entitiesByPiece(source) {
3446
+ const made = /* @__PURE__ */ new Map();
3447
+ 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]);
3448
+ return made;
3449
+ }
3450
+ /** 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. */
3451
+ function originOf(card, choices, pieces, records, name, items = itemise(card, choices)) {
3452
+ if (records.roster === void 0 || records.classified === void 0) return [];
3453
+ const entity = findEntity(records.roster, name);
3454
+ if (entity === void 0) return [];
3455
+ const names = [entity.name, ...entity.aliases].map(norm);
3456
+ const chosen = sourcesFor(entity, items, records.classified);
3457
+ const about = (id) => (records.classified?.[id]?.targets ?? []).some((target) => target.kind === entity.kind && names.includes(norm(target.name)));
3458
+ const seen = /* @__PURE__ */ new Set();
3459
+ return chosen.flatMap((item) => {
3460
+ const id = baseId(item.id);
3461
+ const piece = pieces.find((entry) => entry.id === id);
3462
+ if (piece === void 0 || seen.has(id)) return [];
3463
+ seen.add(id);
3464
+ return [{
3465
+ piece: id,
3466
+ label: piece.label,
3467
+ how: about(item.id) ? "about it" : "mentions it"
3468
+ }];
3469
+ });
3470
+ }
3471
+ // src/host/checks/terms.ts
3472
+ const HAN = /[㐀-鿿]+/gu;
3473
+ /** Words of fewer letters are mostly the glue of a language, which says nothing about whether two texts share facts. */
3474
+ const MIN_LETTERS = 4;
3475
+ /** 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). */
3476
+ function termsOf(text) {
3477
+ const found = /* @__PURE__ */ new Set();
3478
+ const lower = text.normalize("NFKC").toLowerCase();
3479
+ for (const [run] of lower.matchAll(HAN)) {
3480
+ if (run.length === 1) found.add(run);
3481
+ for (let at = 0; at + 1 < run.length; at++) found.add(run.slice(at, at + 2));
3482
+ }
3483
+ 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);
3484
+ return found;
3485
+ }
3486
+ /** How much of `of` is found in `within`, from 0 to 1; a text with no terms counts as found. */
3487
+ function shareOf(of, within) {
3488
+ if (of.size === 0) return 1;
3489
+ let shared = 0;
3490
+ for (const term of of) if (within.has(term)) shared += 1;
3491
+ return shared / of.size;
3492
+ }
3493
+ /** A text as names are looked up in it: width- and case-folded. */
3494
+ const folded = (text) => text.normalize("NFKC").toLowerCase();
3495
+ /** A text as a quote of it is looked up: folded, with runs of white space as one space. */
3496
+ const squashed = (text) => folded(text).replace(/\s+/gu, " ").trim();
3497
+ // src/host/checks/card-evidence.ts
3498
+ const exists = async (file) => await stat(file).then(() => true, () => false);
3499
+ /** @returns the card of the world, or nothing when the world has none (or no newer version waits, for `new`). */
3500
+ async function loadCardEvidence(directory, version) {
3501
+ const folder = join(directory, IMPORT_FOLDER);
3502
+ if (!await exists(join(folder, "card.json"))) return void 0;
3503
+ if (version === "current") return {
3504
+ version,
3505
+ source: await readSource(directory, true)
3506
+ };
3507
+ if (!await exists(join(folder, "update", "card.json"))) return void 0;
3508
+ return {
3509
+ version,
3510
+ source: await readSource(directory, false, "new"),
3511
+ previous: await readSource(directory, true)
3512
+ };
3513
+ }
3514
+ /** 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. */
3515
+ const MADE_FROM = .6;
3516
+ const MIN_TERMS = 4;
3517
+ /** The pieces the import read for the world: not the instructions, templates and entries left out, not those it could not classify. */
3518
+ function usedPieces(source) {
3519
+ return source.pieces.filter((piece) => {
3520
+ if (!piece.used || piece.enabled === false) return false;
3521
+ const roles = rolesOf(source.records.classified, piece.id);
3522
+ return roles.length > 0 && !isLeftOut({ roles });
3523
+ });
3524
+ }
3525
+ /**
3526
+ * 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
3527
+ * 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
3528
+ * mentions an entity does not count as one it was made from: what it says of others is not that entity's.
3529
+ */
3530
+ function madeInto(source, world, only = "any") {
3531
+ const made = /* @__PURE__ */ new Map();
3532
+ const add = (piece, where) => {
3533
+ const list = made.get(piece) ?? [];
3534
+ if (!list.includes(where)) made.set(piece, [...list, where]);
3535
+ };
3536
+ const group = {
3537
+ character: "characters",
3538
+ place: "locations",
3539
+ faction: "factions",
3540
+ thing: "items"
3541
+ };
3542
+ const items = itemise(source.card, source.choices);
3543
+ for (const entity of source.records.roster ?? []) {
3544
+ const where = `${group[entity.kind]}/${entity.key}`;
3545
+ if (!world.texts.has(where)) continue;
3546
+ for (const entry of originOf(source.card, source.choices, source.pieces, source.records, entity.name, items)) if (only === "any" || entry.how === "about it") add(entry.piece, where);
3547
+ }
3548
+ const pieces = usedPieces(source).map((piece) => ({
3549
+ id: baseId(piece.id),
3550
+ terms: termsOf(piece.text)
3551
+ }));
3552
+ const holders = /* @__PURE__ */ new Map();
3553
+ pieces.forEach((piece, at) => {
3554
+ for (const term of piece.terms) {
3555
+ const list = holders.get(term);
3556
+ if (list === void 0) holders.set(term, [at]);
3557
+ else list.push(at);
3558
+ }
3559
+ });
3560
+ for (const [where, text] of world.texts) {
3561
+ if (!where.startsWith(`${ENTITY_FOLDERS[4].directory}/`) && !where.startsWith(`world.json#`)) continue;
3562
+ const terms = termsOf(text);
3563
+ if (terms.size < MIN_TERMS) continue;
3564
+ const shared = /* @__PURE__ */ new Map();
3565
+ for (const term of terms) for (const at of holders.get(term) ?? []) shared.set(at, (shared.get(at) ?? 0) + 1);
3566
+ for (const [at, count] of shared) if (count / terms.size >= MADE_FROM) add(pieces[at].id, where);
3567
+ }
3568
+ return made;
3569
+ }
3570
+ // src/host/checks/check.ts
3571
+ /** Thrown by a check that cannot run on this world; the report says why instead of counting it as clean. */
3572
+ var CheckSkipped = class extends Error {};
3573
+ /** A check's findings with the check's id on each. */
3574
+ const foundBy = (check, found) => found.map((finding) => ({
3575
+ ...finding,
3576
+ check
3577
+ }));
3578
+ // src/host/triggers/parts.ts
3579
+ /** 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. */
3580
+ async function loadWorldParts(directory) {
3581
+ const { characters, problems: characterProblems } = await loadCharacters(directory);
3582
+ const { locations, problems: locationProblems } = await loadLocations(directory);
3583
+ const { items, slots, problems: itemProblems } = await loadItems(directory, {
3584
+ characters: characters.map((character) => character.id),
3585
+ locations
3586
+ });
3587
+ const { defs, problems: variableProblems } = await loadVariables(directory);
3588
+ const { calendar, problems: calendarProblems } = await loadCalendar(directory);
3589
+ const problems = [
3590
+ ...characterProblems,
3591
+ ...locationProblems,
3592
+ ...itemProblems,
3593
+ ...variableProblems,
3594
+ ...calendarProblems
3595
+ ];
3596
+ 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("; ")}`]);
3597
+ return {
3598
+ characters,
3599
+ locations,
3600
+ items,
3601
+ slots,
3602
+ variables: defs,
3603
+ calendar
3604
+ };
3605
+ }
3606
+ // src/host/worlds/scratch.ts
3607
+ /**
3608
+ * 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
3609
+ * a store has; the search a session adds is not needed.
3610
+ */
3611
+ function withScratchStory(parts, use) {
3612
+ const scratch = createSessionStore(":memory:", {
3613
+ id: "scratch",
3614
+ name: "scratch",
3615
+ world: {
3616
+ id: "scratch",
3617
+ name: "scratch"
3618
+ }
3619
+ }, { vectors: false });
3620
+ try {
3621
+ const session = scratch;
3622
+ if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
3623
+ populateLocations(session, parts.locations);
3624
+ populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
3625
+ populateItems(session, parts.items, parts.slots, parts.locations);
3626
+ populateVariables(session, parts.variables, {
3627
+ characters: parts.characters,
3628
+ items: parts.items,
3629
+ locations: parts.locations,
3630
+ values: void 0
3631
+ });
3632
+ return use(session);
3633
+ } finally {
3634
+ scratch.close();
3635
+ }
3636
+ }
3637
+ // src/host/worlds/world-info.ts
3638
+ const textOf = (value) => typeof value === "string" ? value : "";
3639
+ const toolsOf = (value) => {
3640
+ const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
3641
+ return typeof board === "string" ? {} : board;
3642
+ };
3643
+ function infoOf(document) {
3644
+ const opening = document["opening_message"];
3645
+ const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
3646
+ const plain = typeof opening === "string" ? opening : Array.isArray(opening) ? opening.map((part) => textOf(part?.["text"])).filter((text) => text !== "").join("\n\n") : "";
3647
+ const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
3648
+ const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
3649
+ const rules = document["rules"];
3650
+ return {
3651
+ name: textOf(document["name"]),
3652
+ description: textOf(document["description"]),
3653
+ tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
3654
+ rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
3655
+ opening: plain,
3656
+ openingParts: parts,
3657
+ authorName: textOf(author["name"]),
3658
+ authorUrl: textOf(author["url"]),
3659
+ timeZone: textOf(document["time_zone"]),
3660
+ startingTime: textOf(document["starting_time"]),
3661
+ preset: textOf(document["preset"]),
3662
+ lorebooks: Array.isArray(document["lorebooks"]) ? document["lorebooks"].filter((name) => typeof name === "string") : [],
3663
+ version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
3664
+ sampling: parseSampling(document["sampling"], "sampling", []),
3665
+ tools: toolsOf(document["tools"]),
3666
+ alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
3667
+ title: textOf(entry["title"]),
3668
+ text: entry["text"],
3669
+ ...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
3670
+ }] : []) : []
3671
+ };
3672
+ }
3673
+ async function readDocument(directory) {
3674
+ const text = await readFile(join(directory, WORLD_FILE_NAME), "utf8");
3675
+ return {
3676
+ text,
3677
+ document: JSON.parse(text.replace(/^/, ""))
3678
+ };
3679
+ }
3680
+ async function readWorldInfo(directory) {
3681
+ return infoOf((await readDocument(directory)).document);
3682
+ }
3683
+ function setOrRemove(document, key, value) {
3684
+ if (value === "") delete document[key];
3685
+ else document[key] = value;
3686
+ }
3687
+ /**
3688
+ * 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
3689
+ * back as the world will be read before it is written.
3690
+ * @throws {InvalidEditProblems} when the world would no longer be valid.
3691
+ */
3692
+ function editWorldInfo(directory, edit) {
3693
+ return serialized(directory, () => changeWorldInfo(directory, edit));
3694
+ }
3695
+ async function changeWorldInfo(directory, edit) {
3696
+ const { text, document } = await readDocument(directory);
3697
+ const before = infoOf(document);
3698
+ 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"]);
3699
+ if (edit.name !== void 0) document["name"] = edit.name;
3700
+ if (edit.description !== void 0) document["description"] = edit.description;
3701
+ if (edit.tags !== void 0) document["metadata"] = {
3702
+ ...typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {},
3703
+ tags: edit.tags
3704
+ };
3705
+ if (edit.rules !== void 0) {
3706
+ if (edit.rules.length === 0) delete document["rules"];
3707
+ else document["rules"] = edit.rules;
3708
+ }
3709
+ if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
3710
+ if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
3711
+ const name = edit.authorName ?? before.authorName;
3712
+ const url = edit.authorUrl ?? before.authorUrl;
3713
+ if (name === "" && url !== "") throw new InvalidEditProblems(["an author link needs the author's name"]);
3714
+ if (name === "") delete document["author"];
3715
+ else document["author"] = {
3716
+ ...typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {},
3717
+ name,
3718
+ ...url === "" ? {} : { url }
3719
+ };
3720
+ if (url === "" && typeof document["author"] === "object") delete document["author"]["url"];
3721
+ }
3722
+ if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
3723
+ if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
3724
+ if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
3725
+ if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
3726
+ if (edit.lorebooks !== void 0) {
3727
+ if (edit.lorebooks.length === 0) delete document["lorebooks"];
3728
+ else document["lorebooks"] = edit.lorebooks;
3729
+ }
3730
+ if (edit.alternateOpenings !== void 0) {
3731
+ if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
3732
+ else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
3733
+ title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
3734
+ text: entry.text,
3735
+ ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
3736
+ }));
3737
+ }
3738
+ if (edit.sampling !== void 0) {
3739
+ if (Object.keys(edit.sampling).length === 0) delete document["sampling"];
3740
+ else document["sampling"] = edit.sampling;
3741
+ }
3742
+ if (edit.tools !== void 0) {
3743
+ if (Object.keys(edit.tools).length === 0) delete document["tools"];
3744
+ else document["tools"] = edit.tools;
3745
+ }
3746
+ const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
3747
+ const parsed = parseWorldFile(next);
3748
+ if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
3749
+ await atomicWrite(join(directory, WORLD_FILE_NAME), next);
3750
+ return infoOf(document);
3751
+ }
3752
+ // src/host/checks/world-text.ts
3753
+ /** Every string a document holds, joined: what the world says in it, without the structure around it. */
3754
+ const stringsOf = (value) => typeof value === "string" ? [value] : Array.isArray(value) ? value.flatMap(stringsOf) : typeof value === "object" && value !== null ? Object.values(value).flatMap(stringsOf) : [];
3755
+ /** 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. */
3756
+ const STRUCTURE = /* @__PURE__ */ new Set([
3757
+ "id",
3758
+ "role",
3759
+ "tier",
3760
+ "kind",
3761
+ "scope",
3762
+ "type",
3763
+ "status",
3764
+ "control",
3765
+ "known_by",
3766
+ "related",
3767
+ "subjects",
3768
+ "sources",
3769
+ "to",
3770
+ "location",
3771
+ "parent",
3772
+ "held_by",
3773
+ "owner",
3774
+ "members",
3775
+ "knowledge",
3776
+ "relationships",
3777
+ "exits",
3778
+ "start",
3779
+ "visual_identity",
3780
+ "routine",
3781
+ "variables"
3782
+ ]);
3783
+ /** What a document says in words, one `field: text` line each, without the structure around it. */
3784
+ function proseOf(value, field = "") {
3785
+ if (typeof value === "string") return value.trim() === "" ? [] : [field === "" ? value : `${field}: ${value}`];
3786
+ if (Array.isArray(value)) return value.flatMap((entry) => proseOf(entry, field));
3787
+ if (typeof value === "object" && value !== null) return Object.entries(value).filter(([key]) => !STRUCTURE.has(key)).flatMap(([key, entry]) => proseOf(entry, key));
3788
+ return [];
3789
+ }
3790
+ async function readJson$1(file) {
3791
+ try {
3792
+ return JSON.parse(await readFile(file, "utf8"));
3793
+ } catch (error) {
3794
+ if (error.code === "ENOENT") return void 0;
3795
+ throw error;
3796
+ }
3797
+ }
3798
+ /** 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. */
3799
+ async function readWorldText(directory) {
3800
+ const texts = /* @__PURE__ */ new Map();
3801
+ const prose = /* @__PURE__ */ new Map();
3802
+ const subjects = /* @__PURE__ */ new Map();
3803
+ const names = [];
3804
+ const KIND = {
3805
+ characters: "character",
3806
+ locations: "place",
3807
+ factions: "organisation",
3808
+ items: "thing",
3809
+ lore: "background entry"
3810
+ };
3811
+ for (const { directory: folder, file } of ENTITY_FOLDERS) for (const id of await subfolders(join(directory, folder))) {
3812
+ const document = await readJson$1(join(directory, folder, id, file)).catch(() => void 0);
3813
+ if (document === void 0 || typeof document !== "object") continue;
3814
+ texts.set(`${folder}/${id}`, stringsOf(document).join("\n"));
3815
+ prose.set(`${folder}/${id}`, proseOf(document).join("\n"));
3816
+ const label = document[folder === "lore" ? "title" : "name"];
3817
+ subjects.set(`${folder}/${id}`, `${KIND[folder]}${typeof label === "string" ? ` ${label}` : ""}`);
3818
+ if (folder !== "lore") {
3819
+ const own = [document["name"], ...Array.isArray(document["aliases"]) ? document["aliases"] : []].filter((name) => typeof name === "string" && name.trim() !== "");
3820
+ names.push({
3821
+ where: `${folder}/${id}`,
3822
+ kind: folder,
3823
+ names: own,
3824
+ playable: document["role"] === "playable"
3825
+ });
3826
+ }
3827
+ }
3828
+ const info = await readJson$1(join(directory, WORLD_FILE_NAME)).catch(() => void 0);
3829
+ if (typeof info === "object" && info !== null) for (const [field, value] of Object.entries(info)) {
3830
+ const text = stringsOf(value).join("\n");
3831
+ if (text.trim() !== "") {
3832
+ texts.set(`${WORLD_FILE_NAME}#${field}`, text);
3833
+ prose.set(`${WORLD_FILE_NAME}#${field}`, text);
3834
+ subjects.set(`${WORLD_FILE_NAME}#${field}`, `the world's ${field}`);
3835
+ }
3836
+ }
3837
+ const prompts = join(directory, PROMPTS_FOLDER);
3838
+ 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"));
3839
+ return {
3840
+ texts,
3841
+ prose,
3842
+ subjects,
3843
+ names
3844
+ };
3845
+ }
3846
+ // src/host/checks/loaded.ts
3847
+ function once(input, key, load) {
3848
+ if (input.memo === void 0) return load();
3849
+ let loaded = input.memo.get(key);
3850
+ if (loaded === void 0) {
3851
+ loaded = load();
3852
+ input.memo.set(key, loaded);
3853
+ }
3854
+ return loaded;
3855
+ }
3856
+ /** The parts of the world as the checks of one run read them. */
3857
+ const loaded = {
3858
+ validity: (input) => once(input, "validity", () => checkWorld(input.world)),
3859
+ characters: (input) => once(input, "characters", () => loadCharacters(input.world.directory)),
3860
+ locations: (input) => once(input, "locations", () => loadLocations(input.world.directory)),
3861
+ factions: (input) => once(input, "factions", () => loadFactions(input.world.directory)),
3862
+ lore: (input) => once(input, "lore", () => loadLore(input.world.directory)),
3863
+ variables: (input) => once(input, "variables", () => loadVariables(input.world.directory)),
3864
+ info: (input) => once(input, "info", () => readWorldInfo(input.world.directory)),
3865
+ text: (input) => once(input, "text", () => readWorldText(input.world.directory)),
3866
+ /** Which parts of the world each piece of the card the records are about was made into. */
3867
+ made: async (input, card, only = "any") => {
3868
+ const world = await loaded.text(input);
3869
+ return once(input, `made:${only}`, async () => madeInto(card.previous ?? card.source, world, only));
3870
+ },
3871
+ items: async (input) => {
3872
+ const [{ characters }, { locations }] = await Promise.all([loaded.characters(input), loaded.locations(input)]);
3873
+ return once(input, "items", () => loadItems(input.world.directory, {
3874
+ characters: characters.map((character) => character.id),
3875
+ locations
3876
+ }));
3877
+ }
3878
+ };
3879
+ // src/host/checks/consistency.ts
3880
+ /** Words that name one thing a story tracks; a world that declares two of one group tracks it twice. */
3881
+ const SYNONYMS = [
3882
+ [
3883
+ "hp",
3884
+ "health",
3885
+ "hitpoints",
3886
+ "healthpoints",
3887
+ "life",
3888
+ "vitality"
3889
+ ],
3890
+ [
3891
+ "mp",
3892
+ "mana",
3893
+ "magicpoints",
3894
+ "magicpower"
3895
+ ],
3896
+ [
3897
+ "xp",
3898
+ "exp",
3899
+ "experience",
3900
+ "experiencepoints"
3901
+ ],
3902
+ [
3903
+ "gold",
3904
+ "money",
3905
+ "coins",
3906
+ "cash",
3907
+ "currency"
3908
+ ],
3909
+ [
3910
+ "stamina",
3911
+ "energy",
3912
+ "endurance"
3913
+ ],
3914
+ ["sanity", "san"],
3915
+ ["level", "lvl"]
3916
+ ];
3917
+ /** The group of meaning a variable's key or name falls in: a synonym group, else the word itself. */
3918
+ const meanings = (def) => {
3919
+ const found = /* @__PURE__ */ new Set();
3920
+ for (const word of [def.key, def.name].map(norm).filter((word) => word !== "")) {
3921
+ const group = SYNONYMS.findIndex((names) => names.includes(word));
3922
+ found.add(group < 0 ? word : `group:${group}`);
3923
+ }
3924
+ return found;
3925
+ };
3926
+ const overlapping = (a, b) => {
3927
+ if (a.subject !== b.subject || a.kind !== b.kind) return false;
3928
+ const left = a.only ?? [];
3929
+ const right = b.only ?? [];
3930
+ return left.length === 0 || right.length === 0 || left.some((key) => right.includes(key));
3931
+ };
3932
+ /** Pairs of tracked values that mean the same thing for the same subjects. */
3933
+ function duplicateValues(defs) {
3934
+ const pairs = [];
3935
+ for (let i = 0; i < defs.length; i++) {
3936
+ const own = meanings(defs[i]);
3937
+ 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]]);
3938
+ }
3939
+ return pairs;
3940
+ }
3941
+ const FIELDS_LISTED = 6;
3942
+ /** What fixes a finding of the graph lint whose fix is the same every time. */
3943
+ const GRAPH_HINTS = {
3944
+ "character-unplaced": "Give the character a starting place in their own file (start.location); a relationship does not place anyone.",
3945
+ "location-no-exit": "Add a way (an exit) between this place and one the story can reach.",
3946
+ "location-unreachable": "Add a way from a place the story can reach to this one, or from the place the story starts in."
3947
+ };
3948
+ const asSkip = (error) => {
3949
+ if (error instanceof InvalidEditProblems) throw new CheckSkipped("other files of the world have problems that come first");
3950
+ throw error;
3951
+ };
3952
+ const validity = {
3953
+ id: "world-valid",
3954
+ kit: "consistency",
3955
+ mode: "code",
3956
+ needs: [],
3957
+ 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).",
3958
+ async run(input) {
3959
+ const check = await loaded.validity(input);
3960
+ const found = check.problems.map((problem) => ({
3961
+ severity: "error",
3962
+ code: "invalid",
3963
+ where: problem.where,
3964
+ message: problem.message,
3965
+ hint: "Fix it, then run the check again: the next part of the world may have problems of its own."
3966
+ }));
3967
+ if (check.more > 0) found.push({
3968
+ severity: "error",
3969
+ code: "invalid",
3970
+ where: "(the world)",
3971
+ message: `${check.more} more problems are not listed`
3972
+ });
3973
+ return foundBy("world-valid", found);
3974
+ }
3975
+ };
3976
+ const graph = {
3977
+ id: "world-graph",
3978
+ kit: "consistency",
3979
+ mode: "code",
3980
+ needs: [],
3981
+ 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.",
3982
+ async run(input) {
3983
+ const { world } = input;
3984
+ if (!(await loaded.validity(input)).ok) throw new CheckSkipped("the world has problems that come first (see world-valid)");
3985
+ const parts = await loadWorldParts(world.directory).catch(asSkip);
3986
+ return foundBy("world-graph", withScratchStory(parts, (story) => lintWorld(story).map((finding) => ({
3987
+ severity: finding.severity,
3988
+ code: finding.code,
3989
+ where: `${finding.subject.kind}:${finding.subject.key}`,
3990
+ message: finding.message,
3991
+ ...GRAPH_HINTS[finding.code] === void 0 ? {} : { hint: GRAPH_HINTS[finding.code] }
3992
+ }))));
3993
+ }
3994
+ };
3995
+ const values = {
3996
+ id: "duplicate-values",
3997
+ kit: "consistency",
3998
+ mode: "code",
3999
+ needs: [],
4000
+ description: "Tracked values that mean the same thing for the same subjects (health and hp), which the story would keep twice.",
4001
+ async run(input) {
4002
+ const { defs } = await loaded.variables(input);
4003
+ return foundBy("duplicate-values", duplicateValues(defs).map(([a, b]) => ({
4004
+ severity: "warning",
4005
+ code: "duplicate-value",
4006
+ where: "variables.json",
4007
+ message: `${a.key} (${a.name}) and ${b.key} (${b.name}) look like the same tracked value for the same ${a.subject}s`,
4008
+ 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."
4009
+ })));
4010
+ }
4011
+ };
4012
+ const names$1 = {
4013
+ id: "name-clashes",
4014
+ kit: "consistency",
4015
+ mode: "code",
4016
+ needs: [],
4017
+ description: "A character's alias that is another character's name or alias, two organisations or two lore entries with one name.",
4018
+ async run(input) {
4019
+ const [{ characters }, { factions }, { lore }] = await Promise.all([
4020
+ loaded.characters(input),
4021
+ loaded.factions(input),
4022
+ loaded.lore(input)
4023
+ ]);
4024
+ const found = [];
4025
+ const owners = /* @__PURE__ */ new Map();
4026
+ for (const character of characters) {
4027
+ const seen = /* @__PURE__ */ new Set();
4028
+ for (const label of [character.name, ...character.aliases]) {
4029
+ const word = norm(label);
4030
+ if (word === "" || seen.has(word)) continue;
4031
+ seen.add(word);
4032
+ const other = owners.get(word);
4033
+ if (other !== void 0 && other !== character.id) found.push({
4034
+ severity: "warning",
4035
+ code: "alias-clash",
4036
+ where: `characters/${character.id}`,
4037
+ message: `"${label}" names both ${other} and ${character.id}, so a mention cannot be told apart`,
4038
+ hint: "Give one of them a name or alias of its own."
4039
+ });
4040
+ else owners.set(word, character.id);
4041
+ }
4042
+ }
4043
+ const twice = (kind, entries) => {
4044
+ const seen = /* @__PURE__ */ new Map();
4045
+ for (const entry of entries) {
4046
+ const word = norm(entry.label);
4047
+ const other = seen.get(word);
4048
+ if (word !== "" && other !== void 0) found.push({
4049
+ severity: "warning",
4050
+ code: "name-twice",
4051
+ where: `${kind}/${entry.id}`,
4052
+ message: `${kind}/${other} and ${kind}/${entry.id} are both called "${entry.label}"`
4053
+ });
4054
+ else seen.set(word, entry.id);
4055
+ }
4056
+ };
4057
+ twice("factions", factions.map((entry) => ({
4058
+ id: entry.id,
4059
+ label: entry.name
4060
+ })));
4061
+ twice("lore", lore.map((entry) => ({
4062
+ id: entry.id,
4063
+ label: entry.title
4064
+ })));
4065
+ return foundBy("name-clashes", found);
4066
+ }
4067
+ };
4068
+ const prompts = {
4069
+ id: "world-prompts",
4070
+ kit: "consistency",
4071
+ mode: "code",
4072
+ needs: [],
4073
+ 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.",
4074
+ async run({ world }) {
4075
+ const scratch = await mkdtemp(join(tmpdir(), "world-prompts-"));
4076
+ try {
4077
+ return foundBy("world-prompts", copyWorldPrompts(world.directory, scratch).map((problem) => ({
4078
+ severity: "error",
4079
+ code: "prompt",
4080
+ where: problem.path.slice(world.directory.length + 1) || problem.path,
4081
+ message: problem.message
4082
+ })));
4083
+ } finally {
4084
+ await rm(scratch, {
4085
+ recursive: true,
4086
+ force: true
4087
+ });
4088
+ }
4089
+ }
4090
+ };
4091
+ const PARSERS = {
4092
+ characters: parseCharacterFile,
4093
+ locations: parseLocationFile,
4094
+ factions: parseFactionFile,
4095
+ items: parseItemFile,
4096
+ lore: parseLoreFile
4097
+ };
4098
+ const consistencyChecks = [
4099
+ validity,
4100
+ graph,
4101
+ values,
4102
+ names$1,
4103
+ prompts,
4104
+ {
4105
+ id: "unread-fields",
4106
+ kit: "consistency",
4107
+ mode: "code",
4108
+ needs: [],
4109
+ description: "Fields in a character, place, organisation, thing or lore file that nothing reads, so what they say never reaches a story: usually a field written under a name the format does not have.",
4110
+ async run({ world }) {
4111
+ const found = [];
4112
+ for (const { key, directory, file } of ENTITY_FOLDERS) for (const id of await subfolders(join(world.directory, directory)).catch(() => [])) {
4113
+ const text = await readFile(join(world.directory, directory, id, file), "utf8").catch(() => void 0);
4114
+ if (text === void 0) continue;
4115
+ let parsed = false;
4116
+ const { unread: fields, read } = Reader.unreadBy(() => {
4117
+ parsed = PARSERS[key](text, id).ok;
4118
+ });
4119
+ if (!parsed || fields.length === 0) continue;
4120
+ found.push({
4121
+ severity: "warning",
4122
+ code: "field-unread",
4123
+ where: `${directory}/${id}`,
4124
+ message: `${fields.slice(0, FIELDS_LISTED).join(", ")}${fields.length > FIELDS_LISTED ? ` and ${fields.length - FIELDS_LISTED} more` : ""} in ${file} ${fields.length === 1 ? "is" : "are"} not read by anything, so a story never sees ${fields.length === 1 ? "it" : "them"}`,
4125
+ hint: `Move the words to the field that holds them, and remove the one that is not read. The fields a ${file} reads: ${read.join(", ")}.`
4126
+ });
4127
+ }
4128
+ return foundBy("unread-fields", found);
4129
+ }
4130
+ }
4131
+ ];
4132
+ // src/host/import/card-diff.ts
4133
+ const MAX_SEGMENTS = 1500;
4134
+ const MAX_HUNK_CHARS = 700;
4135
+ /** Entries that kept neither their title nor their keys count as the same one only when this much of their words is shared. */
4136
+ const SAME_ENTRY = .5;
4137
+ const normalised = (text) => text.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
4138
+ const entryHead = (piece) => normalised([piece.title, ...piece.keys].join("|"));
4139
+ const words = (text) => new Set(text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []);
4140
+ function overlap$1(a, b) {
4141
+ const first = words(a);
4142
+ const second = words(b);
4143
+ if (first.size === 0 && second.size === 0) return 1;
4144
+ let shared = 0;
4145
+ for (const word of first) if (second.has(word)) shared += 1;
4146
+ return shared / (first.size + second.size - shared);
4147
+ }
4148
+ /**
4149
+ * 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
4150
+ * shifts, so they are found by what they are called and keyed on, then by their text, and only then by the number.
4151
+ */
4152
+ function matchPieces(before, after) {
4153
+ const pairs = [];
4154
+ const left = new Map(before.map((piece) => [piece.id, piece]));
4155
+ const right = new Map(after.map((piece) => [piece.id, piece]));
4156
+ const pair = (a, b) => {
4157
+ pairs.push({
4158
+ before: a,
4159
+ after: b
4160
+ });
4161
+ left.delete(a.id);
4162
+ right.delete(b.id);
4163
+ };
4164
+ const isEntry = (piece) => piece.id.startsWith("entry:");
4165
+ for (const piece of before) {
4166
+ const other = right.get(piece.id);
4167
+ if (!isEntry(piece) && other !== void 0) pair(piece, other);
4168
+ }
4169
+ const unmatched = (map) => [...map.values()].filter(isEntry);
4170
+ for (const keyOf of [entryHead, (piece) => normalised(piece.text)]) {
4171
+ const taken = /* @__PURE__ */ new Set();
4172
+ for (const piece of unmatched(left)) {
4173
+ const key = keyOf(piece);
4174
+ if (key === "" || key === "|") continue;
4175
+ const candidates = unmatched(right).filter((other) => !taken.has(other.id) && keyOf(other) === key);
4176
+ const same = candidates.find((other) => other.id === piece.id) ?? candidates[0];
4177
+ if (same !== void 0) {
4178
+ taken.add(same.id);
4179
+ pair(piece, same);
4180
+ }
4181
+ }
4182
+ }
4183
+ for (const piece of unmatched(left)) {
4184
+ const other = right.get(piece.id);
4185
+ if (other !== void 0 && overlap$1(piece.text, other.text) >= SAME_ENTRY) pair(piece, other);
4186
+ }
4187
+ const order = new Map(before.map((piece, index) => [piece.id, index]));
4188
+ return {
4189
+ pairs: pairs.sort((a, b) => (order.get(a.before.id) ?? 0) - (order.get(b.before.id) ?? 0)),
4190
+ added: [...right.values()],
4191
+ removed: [...left.values()]
4192
+ };
4193
+ }
4194
+ /** The sentences and lines of a text, each with the whitespace that follows it, so that joining them gives the text back. */
4195
+ function segments(text) {
4196
+ const parts = [];
4197
+ const endings = ".!?。!?\n";
4198
+ let start = 0;
4199
+ let at = 0;
4200
+ while (at < text.length) {
4201
+ if (!endings.includes(text[at])) {
4202
+ at += 1;
4203
+ continue;
4204
+ }
4205
+ while (at < text.length && endings.includes(text[at])) at += 1;
4206
+ while (at < text.length && /\s/u.test(text[at])) at += 1;
4207
+ parts.push(text.slice(start, at));
4208
+ start = at;
4209
+ }
4210
+ if (start < text.length) parts.push(text.slice(start));
4211
+ return parts;
4212
+ }
4213
+ const shorten = (text) => {
4214
+ const clean = text.replace(/\s+/g, " ").trim();
4215
+ return clean.length <= MAX_HUNK_CHARS ? clean : `${clean.slice(0, MAX_HUNK_CHARS)}…`;
4216
+ };
4217
+ /** 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). */
4218
+ function diffText(before, after) {
4219
+ if (before === after) return [];
4220
+ const a = segments(before).map((part) => part.trim());
4221
+ const b = segments(after).map((part) => part.trim());
4222
+ if (a.length > MAX_SEGMENTS || b.length > MAX_SEGMENTS) return void 0;
4223
+ const width = b.length + 1;
4224
+ const table = new Uint16Array((a.length + 1) * width);
4225
+ 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]);
4226
+ const hunks = [];
4227
+ let i = 0;
4228
+ let j = 0;
4229
+ let last;
4230
+ let removed = [];
4231
+ let added = [];
4232
+ let before_;
4233
+ const close = () => {
4234
+ if (removed.length + added.length === 0) return;
4235
+ hunks.push({
4236
+ ...before_ === void 0 ? {} : { after: shorten(before_) },
4237
+ removed: shorten(removed.join(" ")),
4238
+ added: shorten(added.join(" "))
4239
+ });
4240
+ removed = [];
4241
+ added = [];
4242
+ };
4243
+ while (i < a.length || j < b.length) {
4244
+ if (i < a.length && j < b.length && a[i] === b[j]) {
4245
+ close();
4246
+ last = a[i];
4247
+ before_ = last;
4248
+ i += 1;
4249
+ j += 1;
4250
+ continue;
4251
+ }
4252
+ if (removed.length + added.length === 0) before_ = last;
4253
+ if (j < b.length && (i === a.length || table[i * width + j + 1] >= table[(i + 1) * width + j])) {
4254
+ added.push(b[j]);
4255
+ j += 1;
4256
+ } else {
4257
+ removed.push(a[i]);
4258
+ i += 1;
4259
+ }
4260
+ }
4261
+ close();
4262
+ return hunks;
4263
+ }
4264
+ /** What differs in what the card says about itself rather than in its pieces. */
4265
+ function cardChanges(before, after) {
4266
+ const lines = [];
4267
+ const compare = (label, a, b) => {
4268
+ if (a !== b) lines.push(`${label}: “${shorten(a)}” → “${shorten(b)}”`);
4269
+ };
4270
+ compare("name", before.name, after.name);
4271
+ compare("creator", before.creator, after.creator);
4272
+ compare("version", before.characterVersion, after.characterVersion);
4273
+ compare("tags", before.tags.join(", "), after.tags.join(", "));
4274
+ return lines;
4275
+ }
4276
+ /** 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. */
4277
+ function worldFieldChanges(before, after) {
4278
+ const changes = [];
4279
+ const differ = (a, b) => a.trim() !== b.trim();
4280
+ if (differ(before.card.description, after.card.description) || differ(before.card.scenario, after.card.scenario) || differ(before.card.creatorNotes, after.card.creatorNotes)) changes.push({
4281
+ field: "description",
4282
+ because: "the card's description, scenario or creator's notes changed, and the world's description summarises them"
4283
+ });
4284
+ if (before.card.tags.join("\n") !== after.card.tags.join("\n")) changes.push({
4285
+ field: "tags",
4286
+ 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`
4287
+ });
4288
+ if (differ(before.card.creator, after.card.creator)) changes.push({
4289
+ field: "authorName",
4290
+ because: `the card\'s creator is now “${after.card.creator}”`
4291
+ });
4292
+ if (differ(openingText(before.card, before.choices.opening) ?? "", openingText(after.card, after.choices.opening) ?? "")) changes.push({
4293
+ field: "opening",
4294
+ 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}})",
4295
+ suggested: openingMessage(openingText(after.card, after.choices.opening) ?? "", after.card.name)
4296
+ });
4297
+ if (JSON.stringify(alternateOpenings(before.card, before.choices.opening)) !== JSON.stringify(alternateOpenings(after.card, after.choices.opening))) changes.push({
4298
+ field: "alternateOpenings",
4299
+ because: "the card's other greetings changed; suggested is the whole list as the import writes it",
4300
+ suggested: alternateOpenings(after.card, after.choices.opening)
4301
+ });
4302
+ return changes;
4303
+ }
4304
+ // src/host/checks/judge.ts
4305
+ /**
4306
+ * 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
4307
+ * question to the language model. The decision model is never the only reader of a thing that may be wrong.
4308
+ */
4309
+ async function verdictOf(model, state, key, instructions, ask) {
4310
+ if (model.decide !== void 0) try {
4311
+ const probability = (await model.decide(state, [{
4312
+ key,
4313
+ instructions
4314
+ }])).get(key);
4315
+ const confidence = model.confidence ?? .7;
4316
+ if (probability !== void 0 && probability >= yesAt(confidence)) return {
4317
+ yes: true,
4318
+ by: "decision"
4319
+ };
4320
+ if (probability !== void 0 && probability <= noAt(confidence)) return {
4321
+ yes: false,
4322
+ by: "decision"
4323
+ };
4324
+ } catch (error) {
4325
+ if (model.cancelled?.() === true) throw error;
4326
+ }
4327
+ return {
4328
+ yes: await ask(),
4329
+ by: "language"
4330
+ };
4331
+ }
4332
+ // src/host/checks/results.ts
4333
+ /** Where a world keeps what its checks found: a dot folder, so what is published leaves it out, like the import's. */
4334
+ const CHECKS_FOLDER = ".checks";
4335
+ const FILE$1 = "results.json";
4336
+ async function read$1(directory) {
4337
+ try {
4338
+ const stored = JSON.parse(await readFile(join(directory, CHECKS_FOLDER, FILE$1), "utf8"));
4339
+ return stored.version === 1 && typeof stored.checks === "object" && stored.checks !== null ? stored : {
4340
+ version: 1,
4341
+ checks: {}
4342
+ };
4343
+ } catch (error) {
4344
+ if (error.code === "ENOENT" || error instanceof SyntaxError) return {
4345
+ version: 1,
4346
+ checks: {}
4347
+ };
4348
+ throw error;
4349
+ }
4350
+ }
4351
+ /**
4352
+ * 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.
4353
+ * @returns `undefined` when none of these checks had run before.
4354
+ */
4355
+ async function recordResults(directory, at, results) {
4356
+ const stored = await read$1(directory);
4357
+ const before = Object.keys(results).flatMap((id) => stored.checks[id]?.findings ?? []);
4358
+ const known = Object.keys(results).some((id) => stored.checks[id] !== void 0);
4359
+ const now = Object.values(results).flat();
4360
+ const was = new Set(before.map(findingKey));
4361
+ const is = new Set(now.map(findingKey));
4362
+ for (const [id, findings] of Object.entries(results)) stored.checks[id] = {
4363
+ at,
4364
+ findings
4365
+ };
4366
+ await atomicWrite(join(directory, CHECKS_FOLDER, FILE$1), JSON.stringify(stored, null, 2), { createDirectory: true });
4367
+ return known ? {
4368
+ added: now.filter((finding) => !was.has(findingKey(finding))).length,
4369
+ resolved: before.filter((finding) => !is.has(findingKey(finding)))
4370
+ } : void 0;
4371
+ }
4372
+ // src/host/checks/similar.ts
4373
+ const FILE = "vectors.json";
4374
+ /** How many texts one request to the embedding provider carries. */
4375
+ const BATCH = 32;
4376
+ const hashOf = (text) => createHash("sha256").update(text).digest("hex").slice(0, 32);
4377
+ const pack = (vector) => Buffer.from(new Float32Array(vector).buffer).toString("base64");
4378
+ const unpack = (text) => {
4379
+ const bytes = Buffer.from(text, "base64");
4380
+ return [...new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4)];
4381
+ };
4382
+ async function read(directory) {
4383
+ try {
4384
+ const stored = JSON.parse(await readFile(join(directory, CHECKS_FOLDER, FILE), "utf8"));
4385
+ return stored.version === 1 && typeof stored.vectors === "object" && stored.vectors !== null ? stored : void 0;
4386
+ } catch (error) {
4387
+ if (error.code === "ENOENT" || error instanceof SyntaxError) return void 0;
4388
+ throw error;
4389
+ }
4390
+ }
4391
+ function cosine(a, b) {
4392
+ let dot = 0;
4393
+ let left = 0;
4394
+ let right = 0;
4395
+ for (let at = 0; at < a.length; at++) {
4396
+ dot += a[at] * b[at];
4397
+ left += a[at] * a[at];
4398
+ right += b[at] * b[at];
4399
+ }
4400
+ return left === 0 || right === 0 ? 0 : dot / Math.sqrt(left * right);
4401
+ }
4402
+ /**
4403
+ * The vectors of texts, in order. What the world has embedded before is kept in its dot folder by the text's hash, so a check run again embeds only what changed; vectors of
4404
+ * another model or size are not used. `undefined` when the run has no embedding provider.
4405
+ */
4406
+ async function vectorsOf(model, directory, texts) {
4407
+ if (model.embed === void 0) return void 0;
4408
+ const stored = await read(directory);
4409
+ const known = new Map(Object.entries(stored?.vectors ?? {}).map(([hash, packed]) => [hash, unpack(packed)]));
4410
+ const hashes = texts.map(hashOf);
4411
+ const missing = [...new Set(hashes.filter((hash) => !known.has(hash)))];
4412
+ if (missing.length === 0) return hashes.map((hash) => known.get(hash));
4413
+ try {
4414
+ return await embedded(model, directory, texts, hashes, missing, known, stored?.model ?? "");
4415
+ } catch (error) {
4416
+ if (error instanceof NoEmbeddingService) return void 0;
4417
+ throw error;
4418
+ }
4419
+ }
4420
+ async function embedded(model, directory, texts, hashes, missing, known, stored) {
4421
+ const byHash = new Map(texts.map((text, at) => [hashes[at], text]));
4422
+ let name = stored;
4423
+ const made = /* @__PURE__ */ new Map();
4424
+ const embed = async (wanted) => {
4425
+ for (let at = 0; at < wanted.length; at += BATCH) {
4426
+ const batch = wanted.slice(at, at + BATCH);
4427
+ const { vectors, model: used } = await model.embed(batch.map((hash) => byHash.get(hash)));
4428
+ if (vectors.length !== batch.length) throw new Error(`the embedding provider returned ${vectors.length} vectors for ${batch.length} texts`);
4429
+ if (name !== "" && name !== used) known.clear();
4430
+ name = used;
4431
+ batch.forEach((hash, index) => made.set(hash, vectors[index]));
4432
+ }
4433
+ };
4434
+ await embed(missing);
4435
+ const size = [...made.values()][0].length;
4436
+ for (const [hash, vector] of known) if (vector.length !== size) known.delete(hash);
4437
+ await embed([...new Set(hashes.filter((hash) => !known.has(hash) && !made.has(hash)))]);
4438
+ const all = new Map([...known, ...made]);
4439
+ const result = hashes.map((hash) => all.get(hash));
4440
+ const kept = [...all].slice(-4e3);
4441
+ await atomicWrite(join(directory, CHECKS_FOLDER, FILE), JSON.stringify({
4442
+ version: 1,
4443
+ model: name,
4444
+ dimensions: size,
4445
+ vectors: Object.fromEntries(kept.map(([hash, vector]) => [hash, pack(vector)]))
4446
+ }), { createDirectory: true });
4447
+ return result;
4448
+ }
4449
+ /** The pairs of vectors closest to each other that `allowed` accepts and that reach `threshold`, closest first, at most `limit`. */
4450
+ function nearPairs(vectors, allowed, threshold, limit) {
4451
+ const pairs = [];
4452
+ for (let a = 0; a < vectors.length; a++) for (let b = a + 1; b < vectors.length; b++) {
4453
+ if (!allowed(a, b)) continue;
4454
+ const score = cosine(vectors[a], vectors[b]);
4455
+ if (score >= threshold) pairs.push({
4456
+ a,
4457
+ b,
4458
+ score
4459
+ });
4460
+ }
4461
+ return pairs.sort((x, y) => y.score - x.score).slice(0, limit);
4462
+ }
4463
+ /**
4464
+ * The pairs of texts worth asking a model about: the closest in meaning when there is an embedding provider, otherwise, when asked to, the first `limit` pairs `allowed` accepts (for a short list), else nothing. Closeness only
4465
+ * says two texts are about the same thing (trust and affection are close, and not one value), so it picks what to ask and never what is true.
4466
+ */
4467
+ async function candidates(model, directory, texts, allowed, threshold, limit, withoutProvider = "none") {
4468
+ const vectors = await vectorsOf(model, directory, texts);
4469
+ if (vectors !== void 0) return nearPairs(vectors, allowed, threshold, limit);
4470
+ if (withoutProvider === "none") return void 0;
4471
+ const pairs = [];
4472
+ for (let a = 0; a < texts.length && pairs.length < limit; a++) for (let b = a + 1; b < texts.length && pairs.length < limit; b++) if (allowed(a, b)) pairs.push({
4473
+ a,
4474
+ b,
4475
+ score: 0
4476
+ });
4477
+ return pairs;
4478
+ }
4479
+ // src/host/checks/fidelity.ts
4480
+ /** The most uncovered pieces listed one by one: past that the import itself is the problem. */
4481
+ const PIECES_LISTED = 12;
4482
+ /** The most numbers one finding lists. */
4483
+ const NUMBERS_LISTED = 8;
4484
+ /** The most parts of the world a finding names as made from a piece. */
4485
+ const PARTS_LISTED = 3;
4486
+ /** 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. */
4487
+ const REFLECTED = .5;
4488
+ const MIN_PASSAGE_TERMS = 3;
4489
+ /** A piece with fewer terms than this is a phrase, not a source of facts: its absence proves nothing. */
4490
+ const MIN_PIECE_TERMS = 4;
4491
+ /** 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. */
4492
+ const MOSTLY_MISSING = .5;
4493
+ const MIN_NAMES_FOR_PATTERN = 4;
4494
+ const SNIPPET = 120;
4495
+ const need$1 = (input) => {
4496
+ if (input.card === void 0) throw new CheckSkipped("the world has no card to compare with");
4497
+ return input.card;
4498
+ };
4499
+ const recordsNeeded = (evidence) => {
4500
+ const source = evidence.previous ?? evidence.source;
4501
+ 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");
4502
+ };
4503
+ const snippet = (text) => `${text.replace(/\s+/gu, " ").trim().slice(0, SNIPPET)}${text.trim().length > SNIPPET ? "…" : ""}`;
4504
+ /** The pieces the import read for the world and the card the records are about. */
4505
+ const basis = (evidence) => evidence.previous ?? evidence.source;
4506
+ /** How many of the uncovered pieces are asked about by meaning, largest first. */
4507
+ const RESCUE_PIECES = 24;
4508
+ /** How many documents of the world are asked about for one piece: the closest in meaning. */
4509
+ const RESCUE_DOCUMENTS = 3;
4510
+ /** How close in meaning a document is to a piece before it is asked about; low on purpose, the question settles it. */
4511
+ const RESCUE_CLOSE = .5;
4512
+ const RESCUE_CHARS = 1800;
4513
+ const coverage = {
4514
+ id: "card-coverage",
4515
+ kit: "fidelity",
4516
+ mode: "code",
4517
+ needs: ["card"],
4518
+ 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. With an embedding provider and a model, a piece no part of the world shares words with (a card in another language, a rewrite) is also looked for by meaning before it is called lost.",
4519
+ async run(input) {
4520
+ const evidence = need$1(input);
4521
+ recordsNeeded(evidence);
4522
+ const source = basis(evidence);
4523
+ const made = await loaded.made(input, evidence);
4524
+ const missing = usedPieces(source).filter((piece) => termsOf(piece.text).size >= MIN_PIECE_TERMS && !made.has(baseId(piece.id))).sort((a, b) => b.text.length - a.text.length);
4525
+ const { saved, looked, problem } = await sayingByMeaning(input, missing);
4526
+ const lost = missing.filter((piece) => !saved.has(piece.id));
4527
+ const found = lost.slice(0, PIECES_LISTED).map((piece) => ({
4528
+ severity: "warning",
4529
+ code: "piece-uncovered",
4530
+ where: `card:${piece.id}`,
4531
+ message: `${piece.label} (${piece.text.length} characters) was read for the world, but nothing in the world seems to be made from it${looked ? ", by words or by meaning" : ""}`,
4532
+ 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."
4533
+ }));
4534
+ if (lost.length > PIECES_LISTED) found.push({
4535
+ severity: "warning",
4536
+ code: "pieces-uncovered-more",
4537
+ where: "card",
4538
+ message: `${lost.length - PIECES_LISTED} more pieces of the card, smaller than these, have nothing in the world made from them`,
4539
+ hint: "The import probably stopped early or read the card as something else: look at the import report before going through them one by one."
4540
+ });
4541
+ if (problem !== void 0) found.push({
4542
+ severity: "info",
4543
+ code: "meaning-unavailable",
4544
+ where: "card",
4545
+ message: `the pieces were not looked for by meaning: ${problem}`
4546
+ });
4547
+ return foundBy("card-coverage", found);
4548
+ }
4549
+ };
4550
+ /** The ids of the pieces whose facts a document of the world says in other words (or another language): the closest documents by meaning, and a model's yes. */
4551
+ async function sayingByMeaning(input, pieces) {
4552
+ const model = input.model;
4553
+ const saved = /* @__PURE__ */ new Set();
4554
+ if (model?.embed === void 0 || pieces.length === 0) return {
4555
+ saved,
4556
+ looked: false
4557
+ };
4558
+ try {
4559
+ return await lookedByMeaning(input, model, pieces, saved);
4560
+ } catch (error) {
4561
+ if (model.cancelled?.() === true) throw error;
4562
+ return {
4563
+ saved,
4564
+ looked: false,
4565
+ problem: error instanceof Error ? error.message : String(error)
4566
+ };
4567
+ }
4568
+ }
4569
+ async function lookedByMeaning(input, model, pieces, saved) {
4570
+ const documents = [...(await loaded.text(input)).prose].filter(([, prose]) => prose.trim() !== "");
4571
+ if (documents.length === 0) return {
4572
+ saved,
4573
+ looked: false
4574
+ };
4575
+ const asked = pieces.slice(0, RESCUE_PIECES);
4576
+ const vectors = await vectorsOf(model, input.world.directory, [...asked.map((piece) => piece.text.slice(0, RESCUE_CHARS)), ...documents.map(([, prose]) => prose.slice(0, RESCUE_CHARS))]);
4577
+ if (vectors === void 0) return {
4578
+ saved,
4579
+ looked: false
4580
+ };
4581
+ const instructions = model.text("checks/decide-covered");
4582
+ await mapLimit(asked, model.concurrency, async (piece, at) => {
4583
+ const near = documents.map(([where, prose], index) => ({
4584
+ where,
4585
+ prose,
4586
+ score: cosine(vectors[at], vectors[asked.length + index])
4587
+ })).filter((entry) => entry.score >= RESCUE_CLOSE).sort((a, b) => b.score - a.score).slice(0, RESCUE_DOCUMENTS);
4588
+ for (const document of near) {
4589
+ if (model.cancelled?.() === true) return;
4590
+ if ((await verdictOf(model, {
4591
+ passage: piece.text.slice(0, RESCUE_CHARS),
4592
+ document: document.prose.slice(0, RESCUE_CHARS)
4593
+ }, "covered", instructions, async () => {
4594
+ return (await model.run({
4595
+ persona: instructions,
4596
+ prompt: `${piece.text.slice(0, RESCUE_CHARS)}\n\n${document.prose.slice(0, RESCUE_CHARS)}`,
4597
+ result: COVERED_SCHEMA,
4598
+ maxTokens: 500
4599
+ })).covered;
4600
+ })).yes) {
4601
+ saved.add(piece.id);
4602
+ return;
4603
+ }
4604
+ }
4605
+ });
4606
+ return {
4607
+ saved,
4608
+ looked: true
4609
+ };
4610
+ }
4611
+ const COVERED_SCHEMA = {
4612
+ type: "object",
4613
+ properties: {
4614
+ reason: { type: "string" },
4615
+ covered: { type: "boolean" }
4616
+ },
4617
+ required: ["reason", "covered"],
4618
+ additionalProperties: false
4619
+ };
4620
+ const names = {
4621
+ id: "card-names",
4622
+ kit: "fidelity",
4623
+ mode: "code",
4624
+ needs: ["card"],
4625
+ 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).",
4626
+ async run(input) {
4627
+ const evidence = need$1(input);
4628
+ const source = basis(evidence);
4629
+ const world = await loaded.text(input);
4630
+ const text = folded([source.card.name, ...source.pieces.map((piece) => piece.text)].join("\n"));
4631
+ const named = (candidate) => {
4632
+ return [candidate, candidate.replace(/\s*[((][^))]*[))]/gu, "").trim()].some((name) => folded(name).trim() !== "" && text.includes(folded(name).trim()));
4633
+ };
4634
+ const checked = world.names.filter((thing) => !thing.playable && thing.names.length > 0);
4635
+ const missing = checked.filter((thing) => !thing.names.some(named));
4636
+ if (checked.length >= MIN_NAMES_FOR_PATTERN && missing.length / checked.length > MOSTLY_MISSING) return foundBy("card-names", [{
4637
+ severity: "info",
4638
+ code: "names-elsewhere",
4639
+ where: "(the world)",
4640
+ 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`,
4641
+ hint: "Compare by meaning instead; the judged checks do."
4642
+ }]);
4643
+ return foundBy("card-names", missing.map((thing) => ({
4644
+ severity: thing.kind === "items" ? "info" : "warning",
4645
+ code: "name-not-in-card",
4646
+ where: thing.where,
4647
+ message: `"${thing.names[0]}" does not occur anywhere in the card`,
4648
+ 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."
4649
+ })));
4650
+ }
4651
+ };
4652
+ const NUMBER = /\p{N}{2,}(?:[.,:]\p{N}+)*/gu;
4653
+ /** The numbers of a piece's text, without those inside the card's macros and addresses. */
4654
+ function numbersOf(text) {
4655
+ const plain = text.replace(/\{\{[\s\S]*?\}\}/gu, " ").replace(/https?:\/\/\S+/gu, " ").normalize("NFKC");
4656
+ return [...new Set(plain.match(NUMBER) ?? [])];
4657
+ }
4658
+ const facts = {
4659
+ id: "card-numbers",
4660
+ kit: "fidelity",
4661
+ mode: "code",
4662
+ needs: ["card"],
4663
+ 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.",
4664
+ async run(input) {
4665
+ const evidence = need$1(input);
4666
+ recordsNeeded(evidence);
4667
+ const source = basis(evidence);
4668
+ const world = await loaded.text(input);
4669
+ const made = await loaded.made(input, evidence);
4670
+ const found = [];
4671
+ for (const piece of usedPieces(source)) {
4672
+ const into = made.get(baseId(piece.id));
4673
+ if (into === void 0) continue;
4674
+ const said = into.map((where) => world.texts.get(where) ?? "").join("\n").normalize("NFKC");
4675
+ const lost = numbersOf(piece.text).filter((number) => !said.includes(number));
4676
+ if (lost.length > 0) found.push({
4677
+ severity: "info",
4678
+ code: "number-lost",
4679
+ where: `card:${piece.id}`,
4680
+ message: `${piece.label} gives ${lost.slice(0, NUMBERS_LISTED).join(", ")}${lost.length > NUMBERS_LISTED ? ` and ${lost.length - NUMBERS_LISTED} more` : ""}, which ${into.slice(0, PARTS_LISTED).join(", ")}${into.length > PARTS_LISTED ? ` and ${into.length - PARTS_LISTED} more` : ""} do not have`,
4681
+ hint: "Read the piece with card_read: a number that matters to the story belongs in the world as the card has it."
4682
+ });
4683
+ }
4684
+ return foundBy("card-numbers", found);
4685
+ }
4686
+ };
4687
+ /** Whether what was made from a piece (or, with none, the whole world) says a changed passage. */
4688
+ function reflected(passage, into, world) {
4689
+ const terms = termsOf(passage);
4690
+ if (terms.size < MIN_PASSAGE_TERMS) return true;
4691
+ return shareOf(terms, termsOf((into ?? [...world.texts.keys()]).map((where) => world.texts.get(where) ?? "").join("\n"))) >= REFLECTED;
4692
+ }
4693
+ const drift = {
4694
+ id: "card-update",
4695
+ kit: "fidelity",
4696
+ mode: "code",
4697
+ needs: ["card"],
4698
+ 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.",
4699
+ async run(input) {
4700
+ const evidence = need$1(input);
4701
+ if (evidence.previous === void 0) throw new CheckSkipped("no newer card is waiting; ask for the card that is waiting with version new");
4702
+ recordsNeeded(evidence);
4703
+ const world = await loaded.text(input);
4704
+ const made = await loaded.made(input, evidence);
4705
+ const match = matchPieces(evidence.previous.pieces, evidence.source.pieces);
4706
+ const found = [];
4707
+ for (const { before, after } of match.pairs) {
4708
+ const hunks = diffText(before.text, after.text);
4709
+ const into = made.get(baseId(before.id));
4710
+ if (hunks === void 0) {
4711
+ found.push({
4712
+ severity: "info",
4713
+ code: "too-long-to-compare",
4714
+ where: `card:${after.id}`,
4715
+ message: `${after.label} is too long to compare sentence by sentence`,
4716
+ hint: "Read both versions with card_read (version current and new)."
4717
+ });
4718
+ continue;
4719
+ }
4720
+ for (const hunk of hunks) {
4721
+ if (hunk.added.trim() === "" || reflected(hunk.added, into, world)) continue;
4722
+ found.push({
4723
+ severity: "warning",
4724
+ code: "update-pending",
4725
+ where: `card:${after.id}`,
4726
+ message: `${after.label} now says “${snippet(hunk.added)}”, which the world does not seem to say yet${hunk.removed === "" ? "" : ` (it said “${snippet(hunk.removed)}”)`}`,
4727
+ hint: "Change what was made from this piece to match, keeping what the person edited."
4728
+ });
4729
+ }
4730
+ }
4731
+ const everything = [...world.texts.keys()];
4732
+ for (const piece of match.added.filter((entry) => entry.used && entry.enabled !== false)) if (!reflected(piece.text, everything, world)) found.push({
4733
+ severity: "info",
4734
+ code: "update-new-piece",
4735
+ where: `card:${piece.id}`,
4736
+ 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)`
4737
+ });
4738
+ const kept = /* @__PURE__ */ new Map();
4739
+ 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);
4740
+ for (const piece of match.removed) for (const where of made.get(baseId(piece.id)) ?? []) if (!kept.has(where)) found.push({
4741
+ severity: "info",
4742
+ code: "update-dropped",
4743
+ where,
4744
+ message: `${where} was made only from ${piece.label}, which the new card dropped`,
4745
+ hint: "Remove it unless the person edited it."
4746
+ });
4747
+ return foundBy("card-update", found);
4748
+ }
4749
+ };
4750
+ /** 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. */
4751
+ const SOURCE_CHARS = 6e3;
4752
+ const MAX_COMPARED = 40;
4753
+ const MAX_REPORTED = 6;
4754
+ const FIDELITY_SCHEMA = {
4755
+ type: "object",
4756
+ properties: {
4757
+ dropped: {
4758
+ type: "array",
4759
+ items: {
4760
+ type: "object",
4761
+ properties: {
4762
+ fact: { type: "string" },
4763
+ quote: { type: "string" }
4764
+ },
4765
+ required: ["fact", "quote"],
4766
+ additionalProperties: false
4767
+ }
4768
+ },
4769
+ invented: {
4770
+ type: "array",
4771
+ items: {
4772
+ type: "object",
4773
+ properties: {
4774
+ fact: { type: "string" },
4775
+ quote: { type: "string" }
4776
+ },
4777
+ required: ["fact", "quote"],
4778
+ additionalProperties: false
4779
+ }
4780
+ }
4781
+ },
4782
+ required: ["dropped", "invented"],
4783
+ additionalProperties: false
4784
+ };
4785
+ /** 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. */
4786
+ function comparisonProblem(value, source, document) {
4787
+ if (value.dropped.length > MAX_REPORTED || value.invented.length > MAX_REPORTED) return `report at most ${MAX_REPORTED} of each`;
4788
+ const missing = (list, text) => list.some((entry) => entry.fact.trim() === "" || !squashed(text).includes(squashed(entry.quote)) || squashed(entry.quote) === "");
4789
+ 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";
4790
+ 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";
4791
+ }
4792
+ const fidelityChecks = [
4793
+ coverage,
4794
+ names,
4795
+ facts,
4796
+ drift,
4797
+ {
4798
+ id: "card-fidelity",
4799
+ kit: "fidelity",
4800
+ mode: "judged",
4801
+ needs: ["card", "model"],
4802
+ 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.",
4803
+ async run(input) {
4804
+ const evidence = need$1(input);
4805
+ recordsNeeded(evidence);
4806
+ const model = input.model;
4807
+ const tr = trOf(model);
4808
+ const source = basis(evidence);
4809
+ const world = await loaded.text(input);
4810
+ const made = await loaded.made(input, evidence, "about");
4811
+ const from = /* @__PURE__ */ new Map();
4812
+ for (const piece of usedPieces(source)) for (const where of made.get(baseId(piece.id)) ?? []) from.set(where, [...from.get(where) ?? [], piece]);
4813
+ const ranked = [...from].map(([where, pieces]) => ({
4814
+ where,
4815
+ pieces,
4816
+ size: pieces.reduce((sum, piece) => sum + piece.text.length, 0)
4817
+ })).sort((a, b) => b.size - a.size);
4818
+ const chosen = ranked.slice(0, MAX_COMPARED);
4819
+ const found = [];
4820
+ if (ranked.length > chosen.length) found.push({
4821
+ severity: "info",
4822
+ code: "not-compared",
4823
+ where: "(the world)",
4824
+ message: `${ranked.length - chosen.length} more documents were not compared: a run compares at most ${MAX_COMPARED}, the ones with the most source first`,
4825
+ hint: "Compare the rest with check_card again after fixing these, or read them against the card yourself."
4826
+ });
4827
+ await mapLimit(chosen, model.concurrency, async ({ where, pieces }) => {
4828
+ if (model.cancelled?.() === true) return;
4829
+ const document = world.prose.get(where) ?? "";
4830
+ const subject = world.subjects.get(where) ?? where;
4831
+ const text = pieces.map((piece) => `[${piece.label}]\n${piece.text.slice(0, SOURCE_CHARS)}`).join("\n\n").slice(0, SOURCE_CHARS * 2);
4832
+ try {
4833
+ const answer = await model.run({
4834
+ persona: model.text("checks/fidelity"),
4835
+ prompt: `${tr("Source pieces:")}\n${text}\n\n${tr("Document ({where}), about {subject}:", {
4836
+ where,
4837
+ subject
4838
+ })}\n${document}`,
4839
+ result: FIDELITY_SCHEMA,
4840
+ maxTokens: 1500,
4841
+ check: (value) => comparisonProblem(value, text, document)
4842
+ });
4843
+ const once = (list) => list.filter((entry, at) => list.findIndex((other) => squashed(other.quote) === squashed(entry.quote)) === at);
4844
+ for (const entry of once(answer.dropped)) found.push({
4845
+ severity: "warning",
4846
+ code: "fact-dropped",
4847
+ where,
4848
+ message: `the card says “${snippet(entry.quote)}” (${entry.fact}), which ${where} does not say`,
4849
+ hint: "Read the piece with card_read; if the fact matters to the story, add it to the document as the card has it."
4850
+ });
4851
+ for (const entry of once(answer.invented)) found.push({
4852
+ severity: "warning",
4853
+ code: "fact-invented",
4854
+ where,
4855
+ message: `${where} says “${snippet(entry.quote)}” (${entry.fact}), which the card does not give`,
4856
+ hint: "Remove it unless the person wants it; the world should not state what its source does not."
4857
+ });
4858
+ } catch (error) {
4859
+ if (model.cancelled?.() === true) throw error;
4860
+ found.push({
4861
+ severity: "info",
4862
+ code: "not-compared",
4863
+ where,
4864
+ message: `${where} could not be compared: ${error instanceof Error ? error.message : String(error)}`
4865
+ });
4866
+ }
4867
+ });
4868
+ return foundBy("card-fidelity", found);
4869
+ }
4870
+ }
4871
+ ];
4872
+ // src/host/checks/playability.ts
4873
+ /** The most players' first scenes a model reads: a world with many playable characters is judged by the first few. */
4874
+ const SCENES_JUDGED = 3;
4875
+ const OPENING_CHARS = 2500;
4876
+ const SCENE_CHARS = 3500;
4877
+ /** Where each character the player may play starts and what is around them, as the files say it. */
4878
+ async function scenesOf(input) {
4879
+ const [{ characters }, { locations }, { items }] = await Promise.all([
4880
+ loaded.characters(input),
4881
+ loaded.locations(input),
4882
+ loaded.items(input)
4883
+ ]);
4884
+ const players = characters.filter((character) => character.role === "playable");
4885
+ if (players.length === 0) throw new CheckSkipped("no character can be played (see quality-cast)");
4886
+ return players.map((player) => {
4887
+ const at = player.start.place?.location;
4888
+ const place = locations.find((location) => location.id === at);
4889
+ return {
4890
+ player,
4891
+ place,
4892
+ others: place === void 0 ? [] : characters.filter((other) => other.id !== player.id && other.kind === "person" && other.start.place?.location === place.id),
4893
+ things: place === void 0 ? [] : items.filter((item) => item.start.kind === "location" && item.start.location === place.id && !item.hidden).map((item) => item.name),
4894
+ ways: place === void 0 ? 0 : place.exits.length + locations.filter((other) => other.id !== place.id && other.exits.some((exit) => exit.to === place.id)).length
4895
+ };
4896
+ });
4897
+ }
4898
+ const firstScene = {
4899
+ id: "first-scene",
4900
+ kit: "playability",
4901
+ mode: "code",
4902
+ needs: [],
4903
+ description: "For each character the player may play: that they start in a place of the world, with other people, things or features there, so the first turn has something to react to. (A place with no way out is named by world-graph.)",
4904
+ async run(input) {
4905
+ const { locations } = await loaded.locations(input);
4906
+ const found = [];
4907
+ for (const scene of await scenesOf(input)) {
4908
+ const where = `characters/${scene.player.id}`;
4909
+ if (scene.place === void 0) {
4910
+ if (locations.length > 0) found.push({
4911
+ severity: "warning",
4912
+ code: "start-nowhere",
4913
+ where,
4914
+ message: `${scene.player.name} starts in no place of the world, though the world has places`,
4915
+ hint: "Give the character a start place."
4916
+ });
4917
+ continue;
4918
+ }
4919
+ if (scene.others.length === 0 && scene.things.length === 0 && scene.place.features.length === 0) found.push({
4920
+ severity: "info",
4921
+ code: "start-empty",
4922
+ where,
4923
+ message: `${scene.player.name} starts alone in ${scene.place.name}, with no people, things or features there to act on`
4924
+ });
4925
+ else if (scene.others.length === 0) found.push({
4926
+ severity: "info",
4927
+ code: "start-alone",
4928
+ where,
4929
+ message: `${scene.player.name} starts alone in ${scene.place.name}: nothing answers until they move or something happens`
4930
+ });
4931
+ }
4932
+ return foundBy("first-scene", found);
4933
+ }
4934
+ };
4935
+ const HOOK_SCHEMA = {
4936
+ type: "object",
4937
+ properties: {
4938
+ reason: { type: "string" },
4939
+ playable: { type: "boolean" }
4940
+ },
4941
+ required: ["reason", "playable"],
4942
+ additionalProperties: false
4943
+ };
4944
+ const playabilityChecks = [firstScene, {
4945
+ id: "opening-playable",
4946
+ kit: "playability",
4947
+ mode: "decision",
4948
+ needs: ["model"],
4949
+ description: "Whether a player who has read the opening and the first scene of their character knows where they are and has something to do. A decision model may answer; what it is unsure of goes to the language model.",
4950
+ async run(input) {
4951
+ const model = input.model;
4952
+ const scenes = (await scenesOf(input)).slice(0, SCENES_JUDGED);
4953
+ const info = await loaded.info(input);
4954
+ const found = [];
4955
+ await mapLimit(scenes, model.concurrency, async (scene) => {
4956
+ const text = [
4957
+ `opening: ${info.opening.trim() === "" ? "(none: the story starts with \"The story begins.\")" : info.opening.slice(0, OPENING_CHARS)}`,
4958
+ `the player's character: ${scene.player.name}: ${scene.player.summary}`,
4959
+ ...scene.player.start.activity === "" ? [] : [`doing: ${scene.player.start.activity}`],
4960
+ ...scene.player.start.intents.slice(0, 3).map((intent) => `wants: ${intent.name}: ${intent.description}`),
4961
+ scene.place === void 0 ? "place: (none)" : `place: ${scene.place.name}: ${scene.place.description}`,
4962
+ ...(scene.place?.features ?? []).slice(0, 8).map((feature) => `feature: ${feature.name}`),
4963
+ ...scene.others.slice(0, 8).map((other) => `here: ${other.name}: ${other.summary}`),
4964
+ ...scene.things.slice(0, 8).map((thing) => `thing here: ${thing}`),
4965
+ `ways out: ${scene.ways}`
4966
+ ].join("\n").slice(0, SCENE_CHARS);
4967
+ let reason = "";
4968
+ const instructions = model.text("checks/decide-opening");
4969
+ if (!(await verdictOf(model, { scene: text }, "playable", instructions, async () => {
4970
+ const answer = await model.run({
4971
+ persona: instructions,
4972
+ prompt: text,
4973
+ result: HOOK_SCHEMA,
4974
+ maxTokens: 500
4975
+ });
4976
+ reason = answer.reason;
4977
+ return answer.playable;
4978
+ })).yes) found.push({
4979
+ severity: "warning",
4980
+ code: "opening-flat",
4981
+ where: `characters/${scene.player.id}`,
4982
+ message: `a player of ${scene.player.name} may not know what to do at the start${reason === "" ? "" : `: ${reason}`}`,
4983
+ hint: "Give the opening or the first scene a situation, a person or a want to act on, from what the card says; do not make it up."
4984
+ });
4985
+ });
4986
+ return foundBy("opening-playable", found);
4987
+ }
4988
+ }];
4989
+ // src/host/checks/semantic.ts
4990
+ /** The most pairs one check asks a model about: past that the world has a different problem than a few doubles. */
4991
+ const PAIRS_ASKED = 12;
4992
+ /** How close two texts are in meaning before they are asked about: low on purpose, because closeness only picks what to ask (trust and affection are as close as gold and coins). */
4993
+ const VALUES_CLOSE = .55;
4994
+ const THINGS_CLOSE = .6;
4995
+ const LORE_CLOSE = .6;
4996
+ const TEXT_CHARS = 1200;
4997
+ const yesNo = (key) => ({
4998
+ type: "object",
4999
+ properties: {
5000
+ reason: { type: "string" },
5001
+ [key]: { type: "boolean" }
5002
+ },
5003
+ required: ["reason", key],
5004
+ additionalProperties: false
5005
+ });
5006
+ /** The pairs a model says yes to, each with the reason the language model gave (the decision model gives none). */
5007
+ async function asked(model, pairs, prompt, key, extra = {}) {
5008
+ const instructions = model.text(prompt);
5009
+ return (await mapLimit(pairs, model.concurrency, async (pair) => {
5010
+ if (model.cancelled?.() === true) return void 0;
5011
+ let reason = "";
5012
+ return (await verdictOf(model, {
5013
+ ...extra,
5014
+ first: pair.first,
5015
+ second: pair.second
5016
+ }, key, instructions, async () => {
5017
+ const answer = await model.run({
5018
+ persona: instructions,
5019
+ prompt: `A:\n${pair.first}\n\nB:\n${pair.second}`,
5020
+ result: yesNo(key),
5021
+ maxTokens: 500
5022
+ });
5023
+ reason = answer.reason;
5024
+ return answer[key] === true;
5025
+ })).yes ? {
5026
+ pair,
5027
+ reason
5028
+ } : void 0;
5029
+ })).filter((entry) => entry !== void 0);
5030
+ }
5031
+ const because = (reason) => reason.trim() === "" ? "" : `: ${reason.trim()}`;
5032
+ const valueText = (def) => `${def.name} (${def.key}): ${def.description ?? ""}`.slice(0, TEXT_CHARS);
5033
+ const sameValue = {
5034
+ id: "duplicate-values-meaning",
5035
+ kit: "consistency",
5036
+ mode: "decision",
5037
+ needs: ["model"],
5038
+ description: "Tracked values that are the same thing under different words or languages (the table of duplicate-values does not know them): the closest in meaning are found with the embedding provider and a decision model says whether they are one.",
5039
+ async run(input) {
5040
+ const model = input.model;
5041
+ const { defs } = await loaded.variables(input);
5042
+ const known = new Set(duplicateValues(defs).map(([a, b]) => `${a.key}\n${b.key}`));
5043
+ const allowed = (a, b) => overlapping(defs[a], defs[b]) && !known.has(`${defs[a].key}\n${defs[b].key}`);
5044
+ const said = await asked(model, (await candidates(model, input.world.directory, defs.map(valueText), allowed, VALUES_CLOSE, PAIRS_ASKED, "first") ?? []).map((entry) => ({
5045
+ near: entry,
5046
+ first: valueText(defs[entry.a]),
5047
+ second: valueText(defs[entry.b])
5048
+ })), "checks/decide-same-value", "same");
5049
+ return foundBy("duplicate-values-meaning", said.map(({ pair, reason }) => {
5050
+ const a = defs[pair.near.a];
5051
+ const b = defs[pair.near.b];
5052
+ return {
5053
+ severity: "warning",
5054
+ code: "duplicate-value",
5055
+ where: "variables.json",
5056
+ message: `${a.key} (${a.name}) and ${b.key} (${b.name}) seem to track the same thing for the same ${a.subject}s${because(reason)}`,
5057
+ 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."
5058
+ };
5059
+ }));
5060
+ }
5061
+ };
5062
+ const KIND_NAME = {
5063
+ characters: "character",
5064
+ locations: "place",
5065
+ factions: "organisation",
5066
+ items: "thing"
5067
+ };
5068
+ /** Whether one name is inside the other (an "Old Mill" and a "Mill"): such a pair is asked about whatever the embedding says. */
5069
+ const nested = (a, b) => a.some((left) => b.some((right) => left !== right && Math.min(left.length, right.length) >= 4 && (left.includes(right) || right.includes(left))));
5070
+ const nearNames = {
5071
+ id: "name-near",
5072
+ kit: "consistency",
5073
+ mode: "decision",
5074
+ needs: ["model"],
5075
+ description: "Two characters, places, organisations or things that may be one written twice under different names (\"The Mill\" and \"Old Mill\"): found by name and, with an embedding provider, by what the sheets say; a decision model says whether they are one.",
5076
+ async run(input) {
5077
+ const model = input.model;
5078
+ const world = await loaded.text(input);
5079
+ const things = world.names.map((thing) => ({
5080
+ where: thing.where,
5081
+ kind: KIND_NAME[thing.kind],
5082
+ names: [...new Set(thing.names.map(norm).filter((name) => name !== ""))],
5083
+ text: `${thing.names[0] ?? thing.where}: ${(world.prose.get(thing.where) ?? "").slice(0, TEXT_CHARS)}`
5084
+ }));
5085
+ const sameKind = (a, b) => things[a].kind === things[b].kind && !things[a].names.some((name) => things[b].names.includes(name));
5086
+ const byName = [];
5087
+ for (let a = 0; a < things.length; a++) for (let b = a + 1; b < things.length; b++) if (sameKind(a, b) && nested(things[a].names, things[b].names)) byName.push({
5088
+ a,
5089
+ b,
5090
+ score: 1
5091
+ });
5092
+ const byMeaning = await candidates(model, input.world.directory, things.map((thing) => thing.text), sameKind, THINGS_CLOSE, PAIRS_ASKED) ?? [];
5093
+ const seen = new Set(byName.map((entry) => `${entry.a}:${entry.b}`));
5094
+ const said = await asked(model, [...byName, ...byMeaning.filter((entry) => !seen.has(`${entry.a}:${entry.b}`))].slice(0, PAIRS_ASKED).map((entry) => ({
5095
+ near: entry,
5096
+ first: `${things[entry.a].kind} ${things[entry.a].text}`,
5097
+ second: `${things[entry.b].kind} ${things[entry.b].text}`
5098
+ })), "checks/decide-same-thing", "same");
5099
+ return foundBy("name-near", said.map(({ pair, reason }) => {
5100
+ const a = things[pair.near.a];
5101
+ const b = things[pair.near.b];
5102
+ return {
5103
+ severity: "warning",
5104
+ code: "possible-duplicate",
5105
+ where: a.where,
5106
+ message: `${a.where} and ${b.where} may be the same ${a.kind}, written twice${because(reason)}`,
5107
+ hint: "Read both. If they are one, keep one and point everything that names the other at it; if they are two, make what tells them apart plain in each. Which stays is a choice."
5108
+ };
5109
+ }));
5110
+ }
5111
+ };
5112
+ const CONFLICT_SCHEMA = {
5113
+ type: "object",
5114
+ properties: {
5115
+ reason: { type: "string" },
5116
+ conflict: { type: "boolean" },
5117
+ first_quote: { type: "string" },
5118
+ second_quote: { type: "string" }
5119
+ },
5120
+ required: [
5121
+ "reason",
5122
+ "conflict",
5123
+ "first_quote",
5124
+ "second_quote"
5125
+ ],
5126
+ additionalProperties: false
5127
+ };
5128
+ /** The shortest quote that can state a fact: a word or a title is not one. */
5129
+ const MIN_QUOTE_CHARS = 10;
5130
+ /** Why a conflict cannot be used: it must quote, from each entry, a statement that rules out the other's, not a title and not the same words twice. */
5131
+ function conflictProblem(value, first, second, titles = ["", ""]) {
5132
+ if (!value.conflict) return void 0;
5133
+ const there = (text, quote) => squashed(quote) !== "" && squashed(text).includes(squashed(quote));
5134
+ const statement = (quote, title) => squashed(quote).replace(/\s/gu, "").length >= MIN_QUOTE_CHARS && !squashed(title).includes(squashed(quote)) && !squashed(quote).includes(squashed(title) || "\0");
5135
+ if (!there(first, value.first_quote)) return "first_quote must be a passage of the first entry, exactly as it is written there";
5136
+ if (!there(second, value.second_quote)) return "second_quote must be a passage of the second entry, exactly as it is written there";
5137
+ if (!statement(value.first_quote, titles[0]) || !statement(value.second_quote, titles[1])) return "each quote must be a statement of fact of its entry (at least a clause long), not a title or a heading";
5138
+ if (squashed(value.first_quote).includes(squashed(value.second_quote)) || squashed(value.second_quote).includes(squashed(value.first_quote))) return "the two quotes are the same words: quote two different statements that cannot both be true";
5139
+ }
5140
+ const loreText = (entry) => `${entry.title}\n${entry.summary}\n${entry.body}`.slice(0, TEXT_CHARS * 2);
5141
+ const semanticChecks = [
5142
+ sameValue,
5143
+ nearNames,
5144
+ {
5145
+ id: "lore-conflict",
5146
+ kit: "consistency",
5147
+ mode: "decision",
5148
+ needs: ["model"],
5149
+ description: "Two background entries that say things that cannot both be true at the same time: the closest in meaning are found with the embedding provider, a decision model screens them, and the language model must quote the passage of each that conflicts.",
5150
+ async run(input) {
5151
+ const model = input.model;
5152
+ const { lore } = await loaded.lore(input);
5153
+ const apart = (a, b) => {
5154
+ const x = lore[a];
5155
+ const y = lore[b];
5156
+ return x.endsAt !== void 0 && y.startsAt !== void 0 && x.endsAt < y.startsAt || y.endsAt !== void 0 && x.startsAt !== void 0 && y.endsAt < x.startsAt;
5157
+ };
5158
+ const near = await candidates(model, input.world.directory, lore.map(loreText), (a, b) => !apart(a, b), LORE_CLOSE, PAIRS_ASKED);
5159
+ if (near === void 0) throw new CheckSkipped("no embedding provider is selected to find which entries to compare");
5160
+ const pairs = near.map((entry) => ({
5161
+ near: entry,
5162
+ first: `entry ${lore[entry.a].id}:\n${loreText(lore[entry.a])}`,
5163
+ second: `entry ${lore[entry.b].id}:\n${loreText(lore[entry.b])}`
5164
+ }));
5165
+ const screened = model.decide === void 0 ? pairs : (await asked(model, pairs, "checks/decide-conflict", "conflict")).map((entry) => entry.pair);
5166
+ const instructions = model.text("checks/conflict");
5167
+ const found = [];
5168
+ await mapLimit(screened.slice(0, 12), model.concurrency, async (pair) => {
5169
+ if (model.cancelled?.() === true) return;
5170
+ const first = loreText(lore[pair.near.a]);
5171
+ const second = loreText(lore[pair.near.b]);
5172
+ try {
5173
+ const answer = await model.run({
5174
+ persona: instructions,
5175
+ prompt: `${pair.first}\n\n${pair.second}`,
5176
+ result: CONFLICT_SCHEMA,
5177
+ maxTokens: 800,
5178
+ check: (value) => conflictProblem(value, first, second, [lore[pair.near.a].title, lore[pair.near.b].title])
5179
+ });
5180
+ if (!answer.conflict) return;
5181
+ const a = lore[pair.near.a];
5182
+ const b = lore[pair.near.b];
5183
+ found.push({
5184
+ severity: "warning",
5185
+ code: "lore-conflict",
5186
+ where: `lore/${a.id}`,
5187
+ message: `lore/${a.id} says “${answer.first_quote.trim()}” and lore/${b.id} says “${answer.second_quote.trim()}”${because(answer.reason)}`,
5188
+ hint: "Read both entries. Keep what the card or the person says is true and correct the other; if both are true at different times, give each its dates."
5189
+ });
5190
+ } catch (error) {
5191
+ if (model.cancelled?.() === true) throw error;
5192
+ }
5193
+ });
5194
+ return foundBy("lore-conflict", found);
5195
+ }
5196
+ }
5197
+ ];
5198
+ // src/host/checks/quality.ts
5199
+ /** A place described in fewer characters than this has nothing to play with. */
5200
+ const THIN_PLACE = 20;
5201
+ const SHEET_CHARS = 3e3;
5202
+ const DIGEST_CHARS = 7e3;
5203
+ const GAPS_LISTED = 8;
5204
+ const text = (value) => (value ?? "").trim();
5205
+ const cast = {
5206
+ id: "quality-cast",
5207
+ kit: "quality",
5208
+ mode: "code",
5209
+ needs: [],
5210
+ 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.",
5211
+ async run(input) {
5212
+ const { characters } = await loaded.characters(input);
5213
+ if (characters.length === 0) throw new CheckSkipped("the world has no characters yet");
5214
+ const found = [];
5215
+ if (!characters.some((character) => character.role === "playable")) found.push({
5216
+ severity: "warning",
5217
+ code: "no-playable",
5218
+ where: "characters",
5219
+ message: "no character can be played, so a story from this world needs an avatar brought along",
5220
+ hint: "Make one character playable, or add one for the player."
5221
+ });
5222
+ const seen = /* @__PURE__ */ new Map();
5223
+ for (const character of characters) {
5224
+ const where = `characters/${character.id}`;
5225
+ const main = character.tier !== "background" && character.kind === "person";
5226
+ if (main && text(character.personality) === "" && text(character.background) === "" && text(character.speech.style) === "") found.push({
5227
+ severity: "warning",
5228
+ code: "sheet-summary-only",
5229
+ where,
5230
+ message: `${character.name} has only a summary: no personality, background or way of speaking`,
5231
+ hint: "Write from what the card or the world says about them; do not make them up."
5232
+ });
5233
+ else if (main && text(character.speech.style) === "" && character.speech.examples.length === 0) found.push({
5234
+ severity: "info",
5235
+ code: "no-voice",
5236
+ where,
5237
+ message: `${character.name} has no stated way of speaking`
5238
+ });
5239
+ const summary = norm(character.summary);
5240
+ if (summary !== "") {
5241
+ const other = seen.get(summary);
5242
+ if (other !== void 0) found.push({
5243
+ severity: "warning",
5244
+ code: "same-summary",
5245
+ where,
5246
+ message: `${character.name} and ${other} have the same summary, so they may be one character written twice`,
5247
+ hint: "Merge them, or tell them apart."
5248
+ });
5249
+ else seen.set(summary, character.name);
5250
+ }
5251
+ }
5252
+ return foundBy("quality-cast", found);
5253
+ }
5254
+ };
5255
+ const places = {
5256
+ id: "quality-places",
5257
+ kit: "quality",
5258
+ mode: "code",
5259
+ needs: [],
5260
+ description: "Places with no description, or one too short to play in.",
5261
+ async run(input) {
5262
+ const { locations } = await loaded.locations(input);
5263
+ return foundBy("quality-places", locations.flatMap((place) => {
5264
+ const length = text(place.description).length;
5265
+ if (length === 0) return [{
5266
+ severity: "warning",
5267
+ code: "place-undescribed",
5268
+ where: `locations/${place.id}`,
5269
+ message: `${place.name} has no description`
5270
+ }];
5271
+ return length < THIN_PLACE && place.features.length === 0 ? [{
5272
+ severity: "info",
5273
+ code: "place-thin",
5274
+ where: `locations/${place.id}`,
5275
+ message: `${place.name} has a one-line description and no features`
5276
+ }] : [];
5277
+ }));
5278
+ }
5279
+ };
5280
+ const about = {
5281
+ id: "quality-world",
5282
+ kit: "quality",
5283
+ mode: "code",
5284
+ needs: [],
5285
+ description: "What the world says about itself: a description, tags for the catalogue, an opening for the story.",
5286
+ async run(input) {
5287
+ const info = await loaded.info(input);
5288
+ const found = [];
5289
+ if (text(info.description) === "") found.push({
5290
+ severity: "info",
5291
+ code: "no-description",
5292
+ where: "world.json",
5293
+ message: "the world has no description, so the worlds list shows nothing about it"
5294
+ });
5295
+ if (info.tags.length === 0) found.push({
5296
+ severity: "info",
5297
+ code: "no-tags",
5298
+ where: "world.json",
5299
+ message: "the world has no tags"
5300
+ });
5301
+ if (text(info.opening) === "" && !info.openingParts) found.push({
5302
+ severity: "info",
5303
+ code: "no-opening",
5304
+ where: "world.json",
5305
+ message: "the world has no opening, so a story starts with \"The story begins.\""
5306
+ });
5307
+ return foundBy("quality-world", found);
5308
+ }
5309
+ };
5310
+ const SHEET_SCHEMA = {
5311
+ type: "object",
5312
+ properties: {
5313
+ reason: { type: "string" },
5314
+ playable: { type: "boolean" }
5315
+ },
5316
+ required: ["reason", "playable"],
5317
+ additionalProperties: false
5318
+ };
5319
+ const sheets = {
5320
+ id: "sheet-playable",
5321
+ kit: "quality",
5322
+ mode: "decision",
5323
+ needs: ["model"],
5324
+ 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.",
5325
+ async run(input) {
5326
+ const { model } = input;
5327
+ const { characters } = await loaded.characters(input);
5328
+ const asked = characters.filter((character) => character.tier !== "background" && character.kind === "person");
5329
+ const found = [];
5330
+ await mapLimit(asked, model.concurrency, async (character) => {
5331
+ const sheet = [
5332
+ `name: ${character.name}`,
5333
+ `summary: ${character.summary}`,
5334
+ `personality: ${character.personality}`,
5335
+ `background: ${character.background}`,
5336
+ `speech: ${character.speech.style}`,
5337
+ ...character.speech.examples.slice(0, 3).map((example) => `says: ${example}`),
5338
+ ...(character.start.intents ?? []).slice(0, 3).map((intent) => `wants: ${intent.name}: ${intent.description}`)
5339
+ ].join("\n").slice(0, SHEET_CHARS);
5340
+ let reason = "";
5341
+ const instructions = model.text("checks/decide-sheet");
5342
+ if (!(await verdictOf(model, { sheet }, "playable", instructions, async () => {
5343
+ const answer = await model.run({
5344
+ persona: instructions,
5345
+ prompt: sheet,
5346
+ result: SHEET_SCHEMA,
5347
+ maxTokens: 500
5348
+ });
5349
+ reason = answer.reason;
5350
+ return answer.playable;
5351
+ })).yes) found.push({
5352
+ severity: "warning",
5353
+ code: "sheet-thin",
5354
+ where: `characters/${character.id}`,
5355
+ message: `${character.name}'s sheet is not enough to play them${reason === "" ? "" : `: ${reason}`}`,
5356
+ hint: "Fill it in from the card or the world, or ask the person; do not make them up."
5357
+ });
5358
+ });
5359
+ return foundBy("sheet-playable", found);
5360
+ }
5361
+ };
5362
+ const GAPS_SCHEMA = {
5363
+ type: "object",
5364
+ properties: { gaps: {
5365
+ type: "array",
5366
+ items: {
5367
+ type: "object",
5368
+ properties: {
5369
+ about: { type: "string" },
5370
+ gap: { type: "string" },
5371
+ fill: { type: "string" }
5372
+ },
5373
+ required: [
5374
+ "about",
5375
+ "gap",
5376
+ "fill"
5377
+ ],
5378
+ additionalProperties: false
5379
+ }
5380
+ } },
5381
+ required: ["gaps"],
5382
+ additionalProperties: false
5383
+ };
5384
+ const qualityChecks = [
5385
+ cast,
5386
+ places,
5387
+ about,
5388
+ sheets,
5389
+ {
5390
+ id: "world-gaps",
5391
+ kit: "quality",
5392
+ mode: "judged",
5393
+ needs: ["model"],
5394
+ 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.",
5395
+ async run(input) {
5396
+ const { world, model } = input;
5397
+ const [{ characters }, { locations }, { factions }, { lore }, { defs }] = await Promise.all([
5398
+ loaded.characters(input),
5399
+ loaded.locations(input),
5400
+ loaded.factions(input),
5401
+ loaded.lore(input),
5402
+ loaded.variables(input)
5403
+ ]);
5404
+ const named = /* @__PURE__ */ new Map();
5405
+ for (const [kind, entries] of [
5406
+ ["character", characters.map((entry) => ({
5407
+ id: entry.id,
5408
+ name: entry.name
5409
+ }))],
5410
+ ["place", locations.map((entry) => ({
5411
+ id: entry.id,
5412
+ name: entry.name
5413
+ }))],
5414
+ ["organisation", factions.map((entry) => ({
5415
+ id: entry.id,
5416
+ name: entry.name
5417
+ }))],
5418
+ ["background", lore.map((entry) => ({
5419
+ id: entry.id,
5420
+ name: entry.title
5421
+ }))]
5422
+ ]) for (const entry of entries) for (const label of [
5423
+ entry.id,
5424
+ entry.name,
5425
+ `${kind} ${entry.id}`,
5426
+ `${kind} ${entry.name}`
5427
+ ]) named.set(norm(label), entry.id);
5428
+ /** What the model named, as the key of that thing; anything else is about the world as a whole. */
5429
+ const keyOf = (about) => named.get(norm(about)) ?? "(the world)";
5430
+ const digest = [
5431
+ `world: ${world.summary.name}: ${text((await loaded.info(input)).description)}`,
5432
+ ...characters.map((entry) => `character ${entry.id} (${entry.role}, ${entry.tier}): ${entry.name}: ${entry.summary}`),
5433
+ ...locations.map((entry) => `place ${entry.id}: ${entry.name}: ${text(entry.description).slice(0, 160)} (${entry.exits.length} ways out)`),
5434
+ ...factions.map((entry) => `organisation ${entry.id}: ${entry.name}: ${entry.summary}`),
5435
+ ...lore.map((entry) => `background ${entry.id}: ${entry.title}: ${entry.summary}`),
5436
+ ...defs.length === 0 ? [] : [`tracked values: ${defs.map((def) => def.key).join(", ")}`]
5437
+ ].join("\n").slice(0, DIGEST_CHARS);
5438
+ const answer = await model.run({
5439
+ persona: model.text("checks/gaps"),
5440
+ prompt: digest,
5441
+ result: GAPS_SCHEMA,
5442
+ maxTokens: 1500,
5443
+ 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
5444
+ });
5445
+ return foundBy("world-gaps", answer.gaps.map((gap) => ({
5446
+ severity: "info",
5447
+ code: "gap",
5448
+ where: keyOf(gap.about),
5449
+ message: gap.gap,
5450
+ hint: gap.fill
5451
+ })));
5452
+ }
5453
+ }
5454
+ ];
5455
+ // src/host/checks/run.ts
5456
+ /** Every check of the suite, grouped by kit; the kits are the unit a command or a tool asks for. */
5457
+ const CHECKS = [
5458
+ ...consistencyChecks,
5459
+ ...semanticChecks,
5460
+ ...fidelityChecks,
5461
+ ...qualityChecks,
5462
+ ...playabilityChecks
5463
+ ];
5464
+ const checksOf = (kits, checks = CHECKS) => checks.filter((check) => kits.includes(check.kit));
5465
+ /**
5466
+ * 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
5467
+ * reports it with what changed since the checks last ran.
5468
+ */
5469
+ async function runChecks(given, run = {}, checks = CHECKS, now = () => /* @__PURE__ */ new Date()) {
5470
+ const input = {
5471
+ ...given,
5472
+ memo: /* @__PURE__ */ new Map()
5473
+ };
5474
+ const kits = run.kits ?? KITS;
5475
+ const chosen = checksOf(kits, checks).filter((check) => run.ids === void 0 || run.ids.includes(check.id));
5476
+ const results = {};
5477
+ const skipped = [];
5478
+ for (const check of chosen) {
5479
+ if (check.mode !== "code" && run.deep !== true && !(run.deep === "decision" && check.mode === "decision")) {
5480
+ skipped.push({
5481
+ check: check.id,
5482
+ reason: "judged by a model: ask for a deep check to run it"
5483
+ });
5484
+ continue;
5485
+ }
5486
+ const missing = check.needs.find((need) => input[need] === void 0);
5487
+ if (missing !== void 0) {
5488
+ skipped.push({
5489
+ check: check.id,
5490
+ reason: missing === "card" ? "the world has no card to compare with" : "no model is available to judge"
5491
+ });
5492
+ continue;
5493
+ }
5494
+ try {
5495
+ results[check.id] = await check.run(input);
5496
+ } catch (error) {
5497
+ if (input.model?.cancelled?.() === true) throw error;
5498
+ skipped.push({
5499
+ check: check.id,
5500
+ reason: error instanceof CheckSkipped ? error.message : `it failed: ${error instanceof Error ? error.message : String(error)}`
5501
+ });
5502
+ }
5503
+ }
5504
+ const at = now().toISOString();
5505
+ const changes = await recordResults(input.world.directory, at, results);
5506
+ const findings = Object.values(results).flat().sort((a, b) => SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity));
5507
+ return {
5508
+ at,
5509
+ kits: [...kits],
5510
+ ran: Object.keys(results),
5511
+ skipped,
5512
+ findings,
5513
+ ...changes === void 0 ? {} : { changes }
5514
+ };
5515
+ }
5516
+ // src/host/checks/present.ts
5517
+ /** The most findings a tool result lists: the rest are counted. */
5518
+ const LISTED = 40;
5519
+ const RESOLVED_LISTED = 10;
5520
+ /** More findings than this of one kind are told as one, with the others' places, so a big world's hundred alike do not bury the rest. */
5521
+ const GROUPED_AT = 5;
5522
+ /** The findings as the assistant reads them: those of one check and code beyond a few are one entry that says how many there are and where. */
5523
+ function grouped(findings) {
5524
+ const kinds = /* @__PURE__ */ new Map();
5525
+ for (const finding of findings) {
5526
+ const key = `${finding.check}\n${finding.code}`;
5527
+ kinds.set(key, [...kinds.get(key) ?? [], finding]);
5528
+ }
5529
+ return [...kinds.values()].flatMap((same) => same.length <= GROUPED_AT ? same : [{
5530
+ ...same[0],
5531
+ count: same.length,
5532
+ also: same.slice(1, 9).map((finding) => finding.where)
5533
+ }]).sort((a, b) => SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity));
5534
+ }
5535
+ /** What the assistant reads of a report: counts first, the worst findings, then what changed since the last run. */
5536
+ function presentReport(report) {
5537
+ const count = (severity) => report.findings.filter((finding) => finding.severity === severity).length;
5538
+ const presented = grouped(report.findings);
5539
+ return {
5540
+ ok: count("error") === 0,
5541
+ counts: Object.fromEntries(SEVERITIES.map((severity) => [severity, count(severity)])),
5542
+ findings: presented.slice(0, LISTED),
5543
+ more: Math.max(0, presented.length - LISTED),
5544
+ skipped: report.skipped,
5545
+ ...report.changes === void 0 ? {} : { since_last_run: {
5546
+ new: report.changes.added,
5547
+ resolved: report.changes.resolved.slice(0, RESOLVED_LISTED),
5548
+ resolved_count: report.changes.resolved.length
5549
+ } }
5550
+ };
5551
+ }
5552
+ // src/host/checks/imported.ts
5553
+ /**
5554
+ * 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
5555
+ * 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. The exception is the
5556
+ * yes-or-no checks, which run when the import has a decision model to answer them.
5557
+ * @returns what the assistant reads of the report.
5558
+ */
5559
+ async function checkImported(directory, name, model) {
5560
+ const card = await loadCardEvidence(directory, "current");
5561
+ const deciding = model?.decide !== void 0;
5562
+ return presentReport(await runChecks({
5563
+ world: {
5564
+ directory,
5565
+ summary: { name }
5566
+ },
5567
+ ...card === void 0 ? {} : { card },
5568
+ ...deciding ? { model } : {}
5569
+ }, {
5570
+ kits: KITS,
5571
+ ...deciding ? { deep: "decision" } : {}
5572
+ }));
5573
+ }
3077
5574
  // src/host/import/run-import.ts
3078
5575
  /** The import in a world is not in the state the step needs, or there is none. The message says what to do. */
3079
5576
  var ImportStateError = class extends Error {};
@@ -3311,6 +5808,10 @@ async function finish(ctx, world) {
3311
5808
  counts: result.report.counts,
3312
5809
  notes: result.report.notes.length
3313
5810
  }, await readFile(join(folder(world), "card.json"), "utf8"));
5811
+ return {
5812
+ ...result,
5813
+ checks: await checkImported(world, choices.name, ctx)
5814
+ };
3314
5815
  }
3315
5816
  return result;
3316
5817
  }
@@ -3355,6 +5856,7 @@ async function structureImport(world, language) {
3355
5856
  counts: result.report.counts,
3356
5857
  notes: result.report.notes.length
3357
5858
  }, await readFile(join(folder(world), "card.json"), "utf8"));
5859
+ await checkImported(world, choices.name);
3358
5860
  return {
3359
5861
  report: result.report,
3360
5862
  ...result.draft === void 0 ? {} : { draft: result.draft }
@@ -3448,8 +5950,21 @@ function contextOf(exec, settings, text, language) {
3448
5950
  if (service === void 0) return Promise.reject(/* @__PURE__ */ new Error("no decision service is selected, or the selected one is not loaded"));
3449
5951
  return askYesNo(service, state, asks, exec.signal);
3450
5952
  } : void 0;
5953
+ const embed = async (texts) => {
5954
+ const service = agent.ctx.get("embeddings");
5955
+ if (service === void 0) throw new NoEmbeddingService("no embedding provider is selected, or the selected one is not loaded");
5956
+ const { vectors, model } = await service.embed(texts, {
5957
+ inputType: "document",
5958
+ signal: exec.signal
5959
+ });
5960
+ return {
5961
+ vectors,
5962
+ model
5963
+ };
5964
+ };
3451
5965
  return {
3452
5966
  run,
5967
+ embed,
3453
5968
  cancelled: () => exec.signal.aborted,
3454
5969
  concurrency: settings.concurrency,
3455
5970
  variablesPerRequest: settings.variablesPerRequest,
@@ -3686,6 +6201,6 @@ function limitAuthoringAgents(ctx, kindOf) {
3686
6201
  return await next();
3687
6202
  });
3688
6203
  }
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 };
6204
+ export { WORLD_FILE_NAME as $, pictureOf as $t, cardTools as A, routineProblems as At, localChanges as B, loadFactions as Bt, readWorldInfo 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, editWorldInfo 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, matchPieces 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, cardChanges as v, populateCalendar as vt, withScratchStory as w, populateKnowledge as wt, worldFieldChanges as x, populateDice as xt, diffText as y, populateCharacters as yt, isUnchanged as z, FACTIONS_DIR as zt };
3690
6205
 
3691
- //# sourceMappingURL=authoring-tools-BgmC2oqU.js.map
6206
+ //# sourceMappingURL=authoring-tools-C_l07RYn.js.map