@dsh-agentic-roleplay/core 0.12.2 → 0.12.4

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 (31) hide show
  1. package/lib/{authoring-tools-BZr4bgBy.js → authoring-tools-B_qYKK8c.js} +2135 -1863
  2. package/lib/authoring.js +208 -35
  3. package/lib/client.js +850 -491
  4. package/lib/client.js.map +1 -1
  5. package/lib/doctor.js +1 -1
  6. package/lib/{gallery-BNg0rPTp.js → gallery-Bu6eZMKk.js} +2 -2
  7. package/lib/{generator-9-5at9cZ.js → generator-CTWQWbSW.js} +2 -2
  8. package/lib/{hooks-Dtq5KZQX.js → hooks-YXQZ9G2d.js} +200 -41
  9. package/lib/images.js +4 -4
  10. package/lib/index.js +62 -42
  11. package/lib/{library-DTxakw0z.js → library-BmlHNCah.js} +2 -2
  12. package/lib/{lorebook-author-tools-BjcEUo22.js → lorebook-author-tools-C3rRpMt7.js} +6 -6
  13. package/lib/lorebook-authoring.js +5 -5
  14. package/lib/orchestration.js +8 -8
  15. package/lib/{pack-jail-Dt0VTsu0.js → pack-jail-VbcXiukr.js} +42 -14
  16. package/lib/{packs-DWfR2Ted.js → packs-CzVh2ZNe.js} +2 -2
  17. package/lib/{presenter-agent-vFOxIuWv.js → presenter-agent-CF3fneuJ.js} +4 -4
  18. package/lib/{preset-Dv5YF2qj.js → preset-C595KRUM.js} +3 -3
  19. package/lib/{preset-author-tools-BUzO9mTW.js → preset-author-tools-CF_JKKTE.js} +6 -6
  20. package/lib/preset-authoring.js +5 -5
  21. package/lib/{reflection-Dd3pEiZB.js → reflection-ByIQSOKC.js} +6 -6
  22. package/lib/{serial-BUaJGwVy.js → serial-ULGUKWsu.js} +1136 -1056
  23. package/lib/{text-Dfv8S8eq.js → text-hiKTooVb.js} +3 -1
  24. package/lib/{turn-guard-87NE-Cnp.js → turn-guard-DXMeAJdv.js} +2 -2
  25. package/package.json +3 -2
  26. package/prompts/en/import/opening.md +17 -0
  27. package/prompts/en/roleplay/decide-opening.md +1 -0
  28. package/prompts/en/world/procedure.md +1 -1
  29. package/prompts/zh/import/opening.md +17 -0
  30. package/prompts/zh/roleplay/decide-opening.md +1 -0
  31. package/prompts/zh/world/procedure.md +1 -1
@@ -1,10 +1,10 @@
1
1
  import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-DTdY14S9.js";
2
- import { $t as subfolders, Bt as loadLore, C as ROLE_TABLE, Ct as PICTURE_FILE, E as askYesNo, Et as readImportFolder, Ft as VARIABLES_FILE_NAME, Gt as ITEM_FILE_NAME, Ht as parseLoreFile, It as loadVariables, Jt as parseSlotsFile, Kt as SLOTS_FILE_NAME, M as WORLD_FILE_NAME, Mt as splitPanels, N as parseWorldFile, Nt as dialectOf, Qt as parseCharacterFile, R as startQuestionsToFile, Rt as variableProblems, S as ROLES, Ut as LOCATION_FILE_NAME, Vt as LORE_FILE_NAME, Wt as parseLocationFile, Xt as parseFactionFile, Yt as FACTION_FILE_NAME, Zt as CHARACTER_FILE_NAME, _ as pruneRelationships, _t as itemise, a as characterDocument, b as classifyItems, bt as IMPORT_FOLDER, c as extractStyle, d as inert, dn as DEFAULT_SLOTS, en as InvalidEditProblems, f as loreDocuments, g as pruneMembers, gt as cleanText, h as pruneLoreSubjects, i as asWritten, j as yesAt, jt as findPanel, k as noAt, kt as parseImportCommand, m as pruneLinks, o as emptyExtracted, p as pruneKnowledge, qt as parseItemFile, r as addLore, s as extractEntities, sn as guarded, t as SerialQueue, u as extractVariables, un as WEEKDAY_NAMES, v as sourcesFor, w as isLeftOut, wt as openingText, x as findEntity, y as buildRoster, yt as withPlayer, zt as LORE_DIR } from "./serial-BUaJGwVy.js";
2
+ import { $t as LOCATION_FILE_NAME, At as openingText, C as ROLE_TABLE, Ct as itemise, E as askYesNo, Et as IMPORT_FOLDER, Gt as dialectOf, Ht as importRequestOf, Jt as loadVariables, L as parseOpeningParts, M as WORLD_FILE_NAME, Mt as readImportFolder, N as parseWorldFile, P as MAX_OPENING_CHARS, Pt as InvalidEditProblems, Qt as parseLoreFile, R as partsText, S as ROLES, St as cleanText, Tt as withPlayer, Ut as findPanel, V as startQuestionsToFile, Vt as IMPORT_COMMAND, Wt as splitPanels, Xt as variableProblems, Zt as LORE_FILE_NAME, _ as pruneRelationships, a as characterDocument, an as FACTION_FILE_NAME, b as classifyItems, bt as loadLore, c as extractStyle, cn as parseCharacterFile, d as inert, en as parseLocationFile, f as loreDocuments, fn as WEEKDAY_NAMES, g as pruneMembers, h as pruneLoreSubjects, i as asWritten, in as parseSlotsFile, j as yesAt, k as noAt, kt as PICTURE_FILE, ln as guarded, m as pruneLinks, nn as SLOTS_FILE_NAME, o as emptyExtracted, on as parseFactionFile, p as pruneKnowledge, pn as DEFAULT_SLOTS, qt as VARIABLES_FILE_NAME, r as addLore, rn as parseItemFile, s as extractEntities, sn as CHARACTER_FILE_NAME, t as SerialQueue, tn as ITEM_FILE_NAME, u as extractVariables, v as sourcesFor, w as isLeftOut, x as findEntity, xt as subfolders, y as buildRoster, yt as LORE_DIR } from "./serial-ULGUKWsu.js";
3
3
  import { f as parseSwitchboard } from "./narration--K2XVIHI.js";
4
4
  import { n as atomicWrite, r as atomicWriteJson } from "./access-Csp80TFX.js";
5
- import { $ as copyWorldPrompts, G as readDocument$1, J as errorMessage, K as Reader, U as commandFlagKey, V as plotReferenceProblems, Z as PROMPTS_FOLDER, a as externalGiven, it as shippedLanguages, lt as InvalidWorldError, nt as listFiles, ot as shippedText, q as formatIssue, rt as promptProblem, s as externalWithheld, t as externalToolLimit, vt as COMPARISONS, z as loadPlots } from "./hooks-Dtq5KZQX.js";
6
- import { t as trimCharacters } from "./text-Dfv8S8eq.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-DTxakw0z.js";
5
+ import { $ as copyWorldPrompts, G as readDocument$1, J as errorMessage, K as Reader, U as commandFlagKey, V as plotReferenceProblems, Z as PROMPTS_FOLDER, c as externalWithheld, ht as registerCommands, it as shippedLanguages, lt as InvalidWorldError, nt as listFiles, o as externalGiven, ot as shippedText, q as formatIssue, rt as promptProblem, t as externalToolLimit, xt as COMPARISONS, z as loadPlots } from "./hooks-YXQZ9G2d.js";
6
+ import { t as trimCharacters } from "./text-hiKTooVb.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-BmlHNCah.js";
8
8
  import { join, relative, sep } from "node:path";
9
9
  import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, lintWorld, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
10
10
  import { createHash } from "node:crypto";
@@ -262,145 +262,66 @@ function readCard(file, name) {
262
262
  }
263
263
  /** Whether a file looks like a PNG, so that its picture can be kept. */
264
264
  const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
265
- // src/host/import/output-ceiling.ts
266
- /** A share of the model's context window, and the least and the fallback when the window is not known: the default of what one helper request may write. */
267
- const AUTO_OUTPUT_SHARE = .1;
268
- const AUTO_OUTPUT_MIN = 16e3;
269
- const AUTO_OUTPUT_UNKNOWN = 32e3;
270
- const windows = /* @__PURE__ */ new Map();
271
- /** The most one request may write when the setting is automatic (0): a tenth of the window, at least 16 000 tokens. */
272
- function autoOutputCeiling(window) {
273
- return window === void 0 ? AUTO_OUTPUT_UNKNOWN : Math.max(AUTO_OUTPUT_MIN, Math.round(window * AUTO_OUTPUT_SHARE));
274
- }
275
- /** The ceiling for requests that cannot wait for the window to be looked up: what was learned from an earlier lookup of the model, or the fallback. */
276
- function knownOutputCeiling(configured, model) {
277
- if (configured > 0) return configured;
278
- return autoOutputCeiling(model === void 0 ? void 0 : windows.get(`${model.provider}/${model.model}`));
279
- }
280
- /** The most one request of a helper may write: the setting when it names a number, else a share of the context window of the model the helper runs on (the chat's own unless one is named). */
281
- async function outputCeiling(configured, agent, named, signal) {
282
- if (configured > 0) return configured;
283
- const config = agent.session.requestHeader()?.config;
284
- const model = named ?? (config?.provider === void 0 || config.model === void 0 ? void 0 : {
285
- provider: config.provider,
286
- model: config.model
287
- });
288
- if (model === void 0) return autoOutputCeiling();
289
- const key = `${model.provider}/${model.model}`;
290
- let window = windows.get(key);
291
- if (window === void 0) {
292
- try {
293
- window = (await agent.ctx.llm.resolveModelInfo(model.provider, model.model, signal)).context?.contextWindow;
294
- } catch {
295
- window = void 0;
296
- }
297
- if (window !== void 0) windows.set(key, window);
298
- }
299
- return autoOutputCeiling(window);
300
- }
301
- // src/host/characters/load.ts
302
- const CHARACTERS_DIR = "characters";
303
- /**
304
- * Read the cast of one world: every subfolder of `<world>/characters/` that
305
- * holds a `character.json`. Ids must be unique; a repeated one is reported and
306
- * the later character skipped.
307
- */
308
- async function loadCharacters(worldDir) {
309
- const dir = join(worldDir, CHARACTERS_DIR);
310
- const result = {
311
- characters: [],
312
- problems: []
313
- };
314
- let folders;
265
+ // src/host/triggers/load.ts
266
+ const TRIGGERS_FILE_NAME = "triggers.json";
267
+ /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
268
+ function parseTriggersFile(text) {
269
+ let data;
315
270
  try {
316
- folders = await subfolders(dir);
271
+ data = JSON.parse(text.replace(/^/, ""));
317
272
  } catch (error) {
318
- result.problems.push({
319
- path: dir,
320
- message: errorMessage(error)
321
- });
322
- return result;
323
- }
324
- const folderById = /* @__PURE__ */ new Map();
325
- for (const folder of folders) {
326
- const file = join(dir, folder, CHARACTER_FILE_NAME);
327
- try {
328
- const character = await readDocument$1(file, (text) => parseCharacterFile(text, folder), result.problems);
329
- if (character === void 0) continue;
330
- const owner = folderById.get(character.id);
331
- if (owner !== void 0) {
332
- result.problems.push({
333
- path: file,
334
- message: `id "${character.id}" is already used by ${owner}`
335
- });
336
- continue;
337
- }
338
- folderById.set(character.id, folder);
339
- result.characters.push(character);
340
- } catch (error) {
341
- if (error.code !== "ENOENT") result.problems.push({
342
- path: file,
343
- message: errorMessage(error)
344
- });
345
- }
273
+ return {
274
+ ok: false,
275
+ issues: [{
276
+ path: "",
277
+ message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
278
+ }]
279
+ };
346
280
  }
347
- return result;
348
- }
349
- // src/host/calendar/load.ts
350
- const CALENDAR_FILE_NAME = "calendar.json";
351
- const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
352
- /**
353
- * Read `calendar.json`: the holidays of the world and the hemisphere its seasons follow (docs/world-format.md). A holiday is told by days (`12-25`,
354
- * `09-21..09-22`, `nth:mon:1`, `season:winter`, a month, a weekday); it cannot name another holiday.
355
- */
356
- function parseCalendarFile(text) {
357
- const issues = [];
358
- const reader = Reader.fromJson(text, issues);
359
- if (reader === void 0) return {
281
+ if (!Array.isArray(data)) return {
360
282
  ok: false,
361
- issues
283
+ issues: [{
284
+ path: "",
285
+ message: "expected a list of triggers"
286
+ }]
362
287
  };
363
- const hemisphere = reader.oneOf("hemisphere", ["north", "south"], "north");
364
- const seen = /* @__PURE__ */ new Set();
365
- const holidays = reader.objects("holidays").flatMap((entry) => {
366
- const id = entry.string("id", { required: true });
367
- const name = entry.string("name", { required: true });
368
- const on = entry.strings("on");
369
- if (id !== void 0 && !HOLIDAY_ID.test(id)) entry.fail("id", "is made of letters, digits, \"-\" and \"_\" (at most 60)");
370
- if (id !== void 0 && seen.has(id)) entry.fail("id", `"${id}" is used by another holiday`);
371
- if (id !== void 0) seen.add(id);
372
- if (on.length === 0) entry.fail("on", `names no day: write days such as "12-25", "09-21..09-22", "nth:mon:1" or a month (${MONTH_NAMES.join(", ")}); seasons are ${SEASONS.join(", ")}`);
373
- for (const problem of dayTokenProblems(on, "on")) entry.fail("on", problem.replace(/^on: /, ""));
374
- return id === void 0 || name === void 0 ? [] : [{
375
- id,
376
- name,
377
- on
378
- }];
288
+ const issues = [];
289
+ const definitions = [];
290
+ data.forEach((entry, index) => {
291
+ const parsed = readTriggerDefinition(entry, `[${index}]`);
292
+ if ("problems" in parsed) for (const problem of parsed.problems) {
293
+ const split = problem.indexOf(": ");
294
+ issues.push({
295
+ path: split < 0 ? `[${index}]` : problem.slice(0, split),
296
+ message: split < 0 ? problem : problem.slice(split + 2)
297
+ });
298
+ }
299
+ else definitions.push(parsed.definition);
300
+ });
301
+ const keys = definitions.map((definition) => definition.key);
302
+ keys.forEach((key, index) => {
303
+ if (keys.indexOf(key) !== index) issues.push({
304
+ path: "",
305
+ message: `the trigger "${key}" is defined twice`
306
+ });
379
307
  });
380
- if (holidays.length > 60) reader.fail("holidays", `a world has at most 60 holidays`);
381
308
  return issues.length > 0 ? {
382
309
  ok: false,
383
310
  issues
384
311
  } : {
385
312
  ok: true,
386
- value: {
387
- hemisphere,
388
- holidays
389
- }
313
+ value: definitions
390
314
  };
391
315
  }
392
- /** The calendar of a world: an optional `<world>/calendar.json`; a world without one has none. */
393
- async function loadCalendar(worldDir) {
316
+ /** Read the world's triggers: an optional `<world>/triggers.json`. A world with none only has what the story makes. */
317
+ async function loadTriggers(worldDir) {
394
318
  const result = {
395
- calendar: {
396
- hemisphere: "north",
397
- holidays: []
398
- },
319
+ triggers: [],
399
320
  problems: []
400
321
  };
401
- const file = join(worldDir, CALENDAR_FILE_NAME);
322
+ const file = join(worldDir, TRIGGERS_FILE_NAME);
402
323
  try {
403
- result.calendar = await readDocument$1(file, parseCalendarFile, result.problems) ?? result.calendar;
324
+ result.triggers = await readDocument$1(file, parseTriggersFile, result.problems) ?? [];
404
325
  } catch (error) {
405
326
  if (error.code !== "ENOENT") result.problems.push({
406
327
  path: file,
@@ -488,1800 +409,2010 @@ async function loadCommands(worldDir) {
488
409
  }
489
410
  return result;
490
411
  }
491
- // src/host/dice/load.ts
492
- const DICE_FILE_NAME = "dice.json";
493
- function readBand(band) {
494
- const label = band.string("label", { required: true });
495
- const result = band.oneOf("result", DICE_RESULTS, "failed");
496
- const min = band.number("min");
497
- const max = band.number("max");
498
- const critical = band.raw("critical");
499
- if (critical !== void 0 && critical !== null && typeof critical !== "boolean") band.fail("critical", "must be true or false");
500
- if (band.raw("result") === void 0) band.fail("result", `is required: one of ${DICE_RESULTS.join(", ")}`);
501
- return label === void 0 ? void 0 : {
502
- label,
503
- result,
504
- ...min === void 0 ? {} : { min },
505
- ...max === void 0 ? {} : { max },
506
- ...critical === true ? { critical: true } : {}
507
- };
508
- }
412
+ // src/host/import/casting.ts
413
+ const CASTING_SCHEMA = {
414
+ type: "object",
415
+ properties: {
416
+ commands: {
417
+ type: "array",
418
+ items: {
419
+ type: "object",
420
+ properties: {
421
+ word: { type: "string" },
422
+ description: { type: "string" }
423
+ },
424
+ required: ["word", "description"],
425
+ additionalProperties: false
426
+ }
427
+ },
428
+ mechanisms: {
429
+ type: "array",
430
+ items: {
431
+ type: "object",
432
+ properties: {
433
+ name: { type: "string" },
434
+ command: { type: "string" },
435
+ happens: { type: "string" },
436
+ need: {
437
+ type: "string",
438
+ enum: ["arrival", "introduction"]
439
+ },
440
+ text: { type: "string" },
441
+ options: {
442
+ type: "array",
443
+ items: { type: "string" }
444
+ }
445
+ },
446
+ required: [
447
+ "name",
448
+ "command",
449
+ "happens",
450
+ "need",
451
+ "text",
452
+ "options"
453
+ ],
454
+ additionalProperties: false
455
+ }
456
+ }
457
+ },
458
+ required: ["commands", "mechanisms"],
459
+ additionalProperties: false
460
+ };
461
+ /** A trigger key is ASCII: the name's own letters when it has any, else the mechanism's number. */
462
+ const asciiKey = (name, number) => {
463
+ const key = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40);
464
+ return key === "" ? `casting_${number}` : key;
465
+ };
466
+ const str = (value) => typeof value === "string" ? value.trim() : "";
467
+ const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null) : [];
468
+ /** The most of the card's casting passages one request reads. */
469
+ const BUDGET_CHARS = 14e3;
470
+ const MAX_MECHANISMS = 8;
509
471
  /**
510
- * Read `dice.json`: the checks a world settles uncertain attempts with (docs/world-format.md). The dice and how their result is read are the world's:
511
- * the game master rolls a check and is told the band the roll fell in, never a number to interpret.
472
+ * The documents of `commands.json` and `triggers.json` an answer describes: a command raises the flag its trigger waits on, a happening is a statement the story is judged
473
+ * against, and the trigger has the world author make the person (a drawn option when the card gives a list). What does not read as a valid file is left out, with a note.
512
474
  */
513
- function parseDiceFile(text) {
514
- const issues = [];
515
- const reader = Reader.fromJson(text, issues);
516
- if (reader === void 0) return {
517
- ok: false,
518
- issues
519
- };
520
- const checks = reader.objects("checks").flatMap((entry) => {
521
- const key = entry.string("key", { required: true });
522
- const name = entry.string("name", { required: true });
523
- const use = entry.string("use", { required: true });
524
- const dice = entry.string("dice", { required: true });
525
- const reading = entry.oneOf("reading", DICE_READINGS, "total");
526
- const compare = entry.oneOf("compare", DICE_COMPARISONS, "absolute");
527
- const hit = entry.number("hit", { min: 1 });
528
- const modifier = entry.string("modifier");
529
- const bands = entry.objects("bands").flatMap((band) => {
530
- const read = readBand(band);
531
- return read === void 0 ? [] : [read];
532
- });
533
- if (key === void 0 || name === void 0 || use === void 0 || dice === void 0) return [];
534
- const definition = {
535
- key,
475
+ /** Whether the passages name `word` as something the player types: after a slash, or alone in brackets or quotes. A word that only turns up in the card's sentences is a topic, not a command. */
476
+ function namedAsCommand(word, passages) {
477
+ const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
478
+ return new RegExp(`/${escaped}(?![\\p{L}\\p{N}_])|[「『【\\[“"'‘((]\\s*/?${escaped}\\s*[」』】\\]”"'’))]`, "iu").test(passages.join("\n"));
479
+ }
480
+ function castingDocuments(answer, passages = []) {
481
+ const notes = [];
482
+ const keyed = objects(answer["commands"]).map((entry) => ({
483
+ word: str(entry["word"]).toLowerCase().replace(/^\//, ""),
484
+ description: str(entry["description"])
485
+ })).filter((entry) => entry.word !== "" && entry.description !== "" && namedAsCommand(entry.word, passages)).map((entry, index) => ({
486
+ ...entry,
487
+ key: /^[a-z][a-z0-9_]{0,29}$/.test(entry.word) ? entry.word : `word_${index + 1}`
488
+ }));
489
+ const parsedCommands = parseCommandsFile(JSON.stringify({ commands: keyed.map((entry) => ({
490
+ word: entry.word,
491
+ key: entry.key,
492
+ description: entry.description
493
+ })) }));
494
+ const usable = parsedCommands.ok ? parsedCommands.value : [];
495
+ if (!parsedCommands.ok) notes.push(`commands not carried: ${parsedCommands.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ")}`);
496
+ const taken = /* @__PURE__ */ new Set();
497
+ const triggers = [];
498
+ for (const mechanism of objects(answer["mechanisms"]).slice(0, MAX_MECHANISMS)) {
499
+ const name = str(mechanism["name"]);
500
+ const command = usable.find((entry) => entry.word === str(mechanism["command"]).toLowerCase());
501
+ const happens = str(mechanism["happens"]) || (command === void 0 && str(mechanism["command"]) !== "" ? str(mechanism["name"]) : "");
502
+ const need = mechanism["need"] === "introduction" ? "introduction" : "arrival";
503
+ const options = Array.isArray(mechanism["options"]) ? mechanism["options"].map(str).filter((option) => option !== "") : [];
504
+ let words = str(mechanism["text"]) || name;
505
+ if (name === "" || command === void 0 && happens === "") {
506
+ notes.push(`casting not carried: "${name || "unnamed"}" has no reason to start it`);
507
+ continue;
508
+ }
509
+ if (options.length > 0 && !words.includes("[draw]")) words = `${words} [draw]`;
510
+ if (options.length === 0) words = words.replaceAll("[draw]", "").trim();
511
+ const when = command === void 0 ? {
512
+ type: "judged",
513
+ text: happens
514
+ } : {
515
+ type: "variable",
516
+ variable: commandFlagKey(command),
517
+ op: COMPARISONS[0],
518
+ value: true
519
+ };
520
+ triggers.push({
521
+ key: uniqueKey(asciiKey(name, triggers.length + 1), taken),
536
522
  name,
537
- use,
538
- dice,
539
- reading,
540
- compare,
541
- bands,
542
- ...hit === void 0 ? {} : { hit },
543
- ...modifier === void 0 || modifier === "" ? {} : { modifier }
523
+ when,
524
+ repeat: true,
525
+ effects: [{
526
+ type: "beat",
527
+ dispatch: "author",
528
+ need,
529
+ text: words,
530
+ ...options.length === 0 ? {} : { draw: options }
531
+ }]
532
+ });
533
+ }
534
+ const parsedTriggers = parseTriggersFile(JSON.stringify(triggers));
535
+ if (!parsedTriggers.ok) {
536
+ notes.push(`casting not carried: ${parsedTriggers.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ")}`);
537
+ return {
538
+ commands: [],
539
+ triggers: [],
540
+ notes
544
541
  };
545
- for (const problem of checkProblems(definition)) entry.fail("", problem);
546
- return [definition];
547
- });
548
- const seen = /* @__PURE__ */ new Set();
549
- for (const check of checks) {
550
- if (seen.has(check.key)) reader.fail("checks", `the key "${check.key}" is used by more than one check`);
551
- seen.add(check.key);
552
542
  }
553
- if (checks.length > 40) reader.fail("checks", `a world has at most 40 checks`);
554
- return issues.length > 0 ? {
555
- ok: false,
556
- issues
557
- } : {
558
- ok: true,
559
- value: checks
543
+ const used = new Set(triggers.flatMap((trigger) => trigger["when"]["variable"] === void 0 ? [] : [String(trigger["when"]["variable"])]));
544
+ return {
545
+ commands: usable.filter((command) => used.has(commandFlagKey(command))).map((command) => ({ ...command })),
546
+ triggers,
547
+ notes
560
548
  };
561
549
  }
562
- /** The checks of a world: an optional `<world>/dice.json`; a world without one has none, and its game master rolls plain dice only. */
563
- async function loadDice(worldDir) {
564
- const result = {
565
- checks: [],
566
- problems: []
550
+ /** Turns what the card says about making people up into the world's commands and the triggers that have the world author make them. */
551
+ async function extractCasting(ctx, card, passages) {
552
+ if (passages.length === 0) return {
553
+ commands: [],
554
+ triggers: [],
555
+ notes: []
567
556
  };
568
- const file = join(worldDir, DICE_FILE_NAME);
557
+ ctx.say("turning the casting guidance into commands and triggers");
569
558
  try {
570
- result.checks = await readDocument$1(file, parseDiceFile, result.problems) ?? [];
559
+ const tr = trOf(ctx);
560
+ const prompt = `${tr("Card: {name}", { name: card.name })}\n\n${tr("Passages about making people up:")}\n\n${passages.join("\n\n---\n\n").slice(0, BUDGET_CHARS)}`;
561
+ return castingDocuments(await ctx.run({
562
+ persona: ctx.text("import/casting", { rules: ctx.text("import/common-rules") }),
563
+ maxTokens: 3e3,
564
+ prompt,
565
+ result: CASTING_SCHEMA,
566
+ check: (value) => {
567
+ const made = castingDocuments(value, passages);
568
+ return made.triggers.length === 0 && made.notes.length > 0 ? made.notes.join("; ") : void 0;
569
+ }
570
+ }), passages);
571
571
  } catch (error) {
572
- if (error.code !== "ENOENT") result.problems.push({
573
- path: file,
574
- message: errorMessage(error)
575
- });
572
+ return {
573
+ commands: [],
574
+ triggers: [],
575
+ notes: [`the casting guidance was not turned into commands and triggers: ${error instanceof Error ? error.message : String(error)}`]
576
+ };
576
577
  }
577
- return result;
578
578
  }
579
- // src/host/factions/load.ts
580
- const FACTIONS_DIR = "factions";
581
- async function loadFactions(worldDir) {
582
- const dir = join(worldDir, FACTIONS_DIR);
583
- const result = {
584
- factions: [],
585
- problems: []
586
- };
587
- let folders;
588
- try {
589
- folders = await subfolders(dir);
590
- } catch (error) {
591
- if (error.code !== "ENOENT") result.problems.push({
592
- path: dir,
593
- message: errorMessage(error)
594
- });
595
- return result;
596
- }
597
- const owners = /* @__PURE__ */ new Map();
598
- for (const folder of folders) {
599
- const file = join(dir, folder, FACTION_FILE_NAME);
600
- try {
601
- const faction = await readDocument$1(file, (text) => parseFactionFile(text, folder), result.problems);
602
- if (faction === void 0) continue;
603
- const owner = owners.get(faction.id);
604
- if (owner !== void 0) {
605
- result.problems.push({
606
- path: file,
607
- message: `id "${faction.id}" is already used by ${owner}`
608
- });
609
- continue;
610
- }
611
- owners.set(faction.id, folder);
612
- result.factions.push(faction);
613
- } catch (error) {
614
- if (error.code !== "ENOENT") result.problems.push({
615
- path: file,
616
- message: errorMessage(error)
617
- });
618
- }
619
- }
620
- if (result.factions.length > 100) result.problems.push({
621
- path: dir,
622
- message: `a world has at most 100 factions`
623
- });
624
- return result;
579
+ // src/host/import/structure.ts
580
+ /** The most example lines the character keeps. */
581
+ const MAX_EXAMPLES = 8;
582
+ /** The summary is the start of the description: a sentence or two. */
583
+ const SUMMARY_CHARS = 280;
584
+ /** The lines of the example messages that the character speaks, as written; the markers of the tool that wrote them are taken out. */
585
+ function exampleLines(text, name) {
586
+ const lines = cleanText(text, name).split("\n").map((line) => line.trim()).filter((line) => line !== "");
587
+ const speaker = /^([^:\n]{1,100}):\s*(.*)$/;
588
+ if (!lines.some((line) => speaker.test(line))) return lines.slice(0, MAX_EXAMPLES);
589
+ const names = new Set([name, name.split(/\s+/)[0] ?? ""].map((part) => part.toLocaleLowerCase()));
590
+ return lines.flatMap((line) => {
591
+ const match = speaker.exec(line);
592
+ if (match?.[1] === void 0 || !names.has(match[1].trim().toLocaleLowerCase())) return [];
593
+ const utterance = match[2]?.trim();
594
+ return utterance === void 0 || utterance === "" ? [] : [utterance];
595
+ }).slice(0, MAX_EXAMPLES);
625
596
  }
626
- // src/host/items/load.ts
627
- const ITEMS_DIR = "items";
628
- /** At most this many items in one world. */
629
- const MAX_ITEMS = 2e3;
630
597
  /**
631
- * Read the things of one world: every subfolder of `<world>/items/` that holds an `item.json`, and an
632
- * optional `<world>/items/slots.json`. A world with no such folder has none. Ids must be unique; what
633
- * a thing is worn in must be a slot, and where it starts, who owns it, what opens it and what it is
634
- * inside must exist in the world, with no thing inside itself.
598
+ * What a card holds, laid out without a model: the card's own character from its description, personality and examples, its lorebook entries as lore in its own words (for the game master only,
599
+ * as nothing has read what they say), and its instructions as the narration style, word for word. No place, faction, thing or other person is found: those take a reader.
635
600
  */
636
- async function loadItems(worldDir, context) {
637
- const dir = join(worldDir, ITEMS_DIR);
638
- const result = {
639
- items: [],
640
- slots: DEFAULT_SLOTS.map((slot) => ({ ...slot })),
641
- problems: []
601
+ function structureOnly(card, items, _choices) {
602
+ const taken = /* @__PURE__ */ new Set();
603
+ const roster = [{
604
+ kind: "character",
605
+ key: uniqueKey(slug(card.name, "character"), taken),
606
+ name: card.name,
607
+ aliases: [],
608
+ player: false
609
+ }];
610
+ const target = [{
611
+ name: card.name,
612
+ kind: "character"
613
+ }];
614
+ const classified = {};
615
+ for (const item of items) if (item.id.startsWith("field:description") || item.id.startsWith("field:personality")) classified[item.id] = {
616
+ roles: ["character"],
617
+ targets: target
642
618
  };
643
- let folders;
644
- try {
645
- folders = await subfolders(dir);
646
- } catch (error) {
647
- if (error.code !== "ENOENT") result.problems.push({
648
- path: dir,
649
- message: errorMessage(error)
650
- });
651
- return result;
652
- }
653
- try {
654
- const own = await readDocument$1(join(dir, SLOTS_FILE_NAME), parseSlotsFile, result.problems);
655
- for (const slot of own ?? []) {
656
- const at = result.slots.findIndex((existing) => existing.id === slot.id);
657
- if (at < 0) result.slots.push(slot);
658
- else result.slots[at] = slot;
659
- }
660
- } catch (error) {
661
- if (error.code !== "ENOENT") result.problems.push({
662
- path: join(dir, SLOTS_FILE_NAME),
663
- message: errorMessage(error)
664
- });
665
- }
666
- const folderOf = /* @__PURE__ */ new Map();
667
- for (const folder of folders) {
668
- const file = join(dir, folder, ITEM_FILE_NAME);
669
- try {
670
- const item = await readDocument$1(file, (text) => parseItemFile(text, folder), result.problems);
671
- if (item === void 0) continue;
672
- const owner = folderOf.get(item.id);
673
- if (owner !== void 0) {
674
- result.problems.push({
675
- path: file,
676
- message: `id "${item.id}" is already used by ${owner}`
677
- });
678
- continue;
679
- }
680
- folderOf.set(item.id, folder);
681
- result.items.push(item);
682
- } catch (error) {
683
- if (error.code !== "ENOENT") result.problems.push({
684
- path: file,
685
- message: errorMessage(error)
686
- });
619
+ else if (item.id.startsWith("field:example")) classified[item.id] = {
620
+ roles: ["speech"],
621
+ targets: target
622
+ };
623
+ else if (item.id.startsWith("field:")) classified[item.id] = {
624
+ roles: ["scenario"],
625
+ targets: []
626
+ };
627
+ else classified[item.id] = {
628
+ roles: ["world"],
629
+ targets: []
630
+ };
631
+ const extracted = emptyExtracted();
632
+ const description = cleanText(card.description, card.name);
633
+ const built = characterDocument(roster[0], {
634
+ tier: "principal",
635
+ kind: "person",
636
+ summary: description.slice(0, SUMMARY_CHARS).trim(),
637
+ personality: cleanText(card.personality, card.name),
638
+ background: description,
639
+ speech: {
640
+ style: "",
641
+ examples: exampleLines(card.messageExample, card.name)
687
642
  }
688
- }
689
- if (result.items.length > 2e3) result.problems.push({
690
- path: dir,
691
- message: `a world has at most ${MAX_ITEMS} items`
643
+ }, roster);
644
+ extracted.characters.push(built.document);
645
+ extracted.notes.push(...built.notes);
646
+ for (const item of items.filter((entry) => entry.id.startsWith("entry:"))) for (const entry of loreDocuments(asWritten(item), roster, taken)) addLore(extracted.lore, {
647
+ ...entry.document,
648
+ scope: "listed"
692
649
  });
693
- const byId = new Map(result.items.map((item) => [item.id, item]));
694
- const slotIds = new Set(result.slots.map((slot) => slot.id));
695
- const places = new Map(context.locations.map((location) => [location.id, location]));
696
- const characters = new Set(context.characters);
697
- const fileOf = (id) => join(dir, folderOf.get(id) ?? id, ITEM_FILE_NAME);
698
- for (const item of result.items) {
699
- const problem = (message) => {
700
- result.problems.push({
701
- path: fileOf(item.id),
702
- message
703
- });
704
- };
705
- if (item.wearable !== void 0 && !slotIds.has(item.wearable)) problem(`wearable: "${item.wearable}" is not a slot (the slots are: ${[...slotIds].join(", ")}; add one in ${SLOTS_FILE_NAME})`);
706
- if (item.owner !== void 0 && !characters.has(item.owner)) problem(`owner: "${item.owner}" is not a character of this world`);
707
- for (const key of item.container?.openedBy ?? []) if (!byId.has(key)) problem(`container.opened_by: "${key}" is not an item of this world`);
708
- const { start } = item;
709
- if (start.kind === "location") {
710
- const place = places.get(start.location);
711
- if (place === void 0) problem(`location: "${start.location}" is not a place of this world`);
712
- else if (start.feature !== void 0 && !place.features.some((feature) => feature.key === start.feature)) problem(`feature: ${place.name} has no feature "${start.feature}"`);
713
- } else if (start.kind === "held" || start.kind === "worn") {
714
- if (!characters.has(start.character)) problem(`${start.kind === "held" ? "held_by" : "worn_by"}: "${start.character}" is not a character of this world`);
715
- } else if (start.kind === "inside") {
716
- const box = byId.get(start.item);
717
- if (box === void 0) problem(`inside: "${start.item}" is not an item of this world`);
718
- else if (box.container === void 0) problem(`inside: ${box.name} is not a container`);
719
- const seen = /* @__PURE__ */ new Set([item.id]);
720
- for (let up = box; up !== void 0; up = up.start.kind === "inside" ? byId.get(up.start.item) : void 0) {
721
- if (seen.has(up.id)) {
722
- problem("inside: the items are inside each other in a circle");
723
- break;
724
- }
725
- seen.add(up.id);
726
- }
727
- }
728
- }
729
- for (const place of context.locations) place.exits.forEach((exit, index) => {
730
- for (const key of exit.openedBy ?? []) if (!byId.has(key)) result.problems.push({
731
- path: join(worldDir, "locations", place.id, "location.json"),
732
- message: `exits[${index}].opened_by: "${key}" is not an item of this world`
733
- });
650
+ const instructions = [card.systemPrompt, card.postHistoryInstructions].map((text) => cleanText(text, card.name)).filter((text) => text !== "");
651
+ if (instructions.length > 0) extracted.prompts.push({
652
+ id: "roleplay/style",
653
+ text: inert(instructions.join("\n\n"))
734
654
  });
735
- return result;
736
- }
737
- /** The items in an order where each comes after the container it starts in. */
738
- function containersFirst(items) {
739
- const ordered = [];
740
- const placed = /* @__PURE__ */ new Set();
741
- const byId = new Map(items.map((item) => [item.id, item]));
742
- const place = (item) => {
743
- if (placed.has(item.id)) return;
744
- placed.add(item.id);
745
- const box = item.start.kind === "inside" ? byId.get(item.start.item) : void 0;
746
- if (box !== void 0) place(box);
747
- ordered.push(item);
655
+ extracted.notes.push("imported without a model: only the card's own character, its lorebook and its instructions were carried over");
656
+ return {
657
+ classified,
658
+ roster,
659
+ extracted
748
660
  };
749
- for (const item of items) place(item);
750
- return ordered;
751
661
  }
752
- // src/host/locations/load.ts
753
- const LOCATIONS_DIR = "locations";
662
+ // src/host/import/outcomes.ts
754
663
  /**
755
- * Read the places of one world: every subfolder of `<world>/locations/` that holds a
756
- * `location.json`. A world with no such folder has no places, which is fine. Ids must be unique;
757
- * every parent and every exit must lead to a place of the world, and the places must not contain
758
- * each other in a circle. Every problem is reported with the file it is in.
664
+ * What became of one piece of a card: `carried` is kept word for word (an opening), `converted` made characters, places, things or other entries of the world, `guidance`
665
+ * became instructions to the narrator, `read` was read for the world but nothing named came of it, `omitted` was left out on purpose, `awaiting` has not been looked at yet.
759
666
  */
760
- async function loadLocations(worldDir) {
761
- const dir = join(worldDir, LOCATIONS_DIR);
762
- const result = {
763
- locations: [],
764
- problems: []
667
+ const OUTCOMES = [
668
+ "carried",
669
+ "converted",
670
+ "guidance",
671
+ "read",
672
+ "omitted",
673
+ "awaiting"
674
+ ];
675
+ const rolesOf$1 = (source, id) => [...new Set(Object.entries(source.records.classified ?? {}).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
676
+ const MECHANICS = [
677
+ "variable",
678
+ "rules",
679
+ "command",
680
+ "trigger"
681
+ ];
682
+ function outcomeOf(source, piece, made, mechanics, finished) {
683
+ const { choices, card } = source;
684
+ const reported = source.records.report !== void 0 || finished;
685
+ if (piece.id === "field:creator-notes") return {
686
+ outcome: "omitted",
687
+ because: "notes to people, not part of the world"
765
688
  };
766
- let folders;
767
- try {
768
- folders = await subfolders(dir);
769
- } catch (error) {
770
- if (error.code !== "ENOENT") result.problems.push({
771
- path: dir,
772
- message: errorMessage(error)
773
- });
774
- return result;
689
+ if (piece.id === "field:first-message" || piece.id.startsWith("field:greeting-")) {
690
+ if (choices.opening.kind === "none") return {
691
+ outcome: "omitted",
692
+ because: "the person chose no opening"
693
+ };
694
+ return reported ? {
695
+ outcome: "carried",
696
+ because: "an opening of the world"
697
+ } : { outcome: "awaiting" };
775
698
  }
776
- const files = /* @__PURE__ */ new Map();
777
- for (const folder of folders) {
778
- const file = join(dir, folder, LOCATION_FILE_NAME);
779
- try {
780
- const location = await readDocument$1(file, (text) => parseLocationFile(text, folder), result.problems);
781
- if (location === void 0) continue;
782
- const owner = files.get(location.id);
783
- if (owner !== void 0) {
784
- result.problems.push({
785
- path: file,
786
- message: `id "${location.id}" is already used by ${owner}`
787
- });
788
- continue;
789
- }
790
- files.set(location.id, folder);
791
- result.locations.push(location);
792
- } catch (error) {
793
- if (error.code !== "ENOENT") result.problems.push({
794
- path: file,
795
- message: errorMessage(error)
796
- });
797
- }
699
+ if (piece.id === "field:system-prompt" || piece.id === "field:post-history") return reported ? {
700
+ outcome: "guidance",
701
+ because: "instructions to the narrator"
702
+ } : { outcome: "awaiting" };
703
+ if (piece.enabled !== void 0 && choices.disabledEntries.includes(piece.id)) return {
704
+ outcome: "omitted",
705
+ because: "left off by the person"
706
+ };
707
+ if (piece.enabled === false && !(card.book?.entries.find((entry) => entry.id === piece.id)?.enabled ?? true) && !piece.used) return {
708
+ outcome: "omitted",
709
+ because: "switched off in the card"
710
+ };
711
+ if (source.records.classified === void 0) return { outcome: "awaiting" };
712
+ const roles = rolesOf$1(source, piece.id);
713
+ if (roles.length === 0) return {
714
+ outcome: "awaiting",
715
+ because: "the import did not classify it"
716
+ };
717
+ if (roles.every((role) => ROLE_TABLE[role].leftOut)) {
718
+ if (mechanics) return {
719
+ outcome: "converted",
720
+ because: "its rules became tracked values, rules or triggers"
721
+ };
722
+ return roles.includes("instruction") ? {
723
+ outcome: "guidance",
724
+ because: "how to run a story, not facts of this one"
725
+ } : {
726
+ outcome: "omitted",
727
+ because: roles.includes("template") ? "a template or format of the source tool" : "nothing to do with the story"
728
+ };
798
729
  }
799
- if (result.locations.length > 500) result.problems.push({
800
- path: dir,
801
- message: `a world has at most 500 places`
730
+ if (made.length > 0 || mechanics) return {
731
+ outcome: "converted",
732
+ ...made.length === 0 ? { because: "its rules became tracked values, rules or triggers" } : {}
733
+ };
734
+ return {
735
+ outcome: "read",
736
+ because: "no character, place, thing or rule is made from it: its words survive only as background"
737
+ };
738
+ }
739
+ /** What became of every piece of the card, from the import's records; `made` is `entitiesByPiece` of the same source. */
740
+ function pieceOutcomes(source, made, options = {}) {
741
+ const derived = options.derived ?? source.records.report?.derived ?? [];
742
+ return source.pieces.map((piece) => {
743
+ const from = derived.filter((entry) => entry.pieces.includes(piece.id));
744
+ const labels = from.map((entry) => `${entry.kind}: ${entry.name}`);
745
+ return {
746
+ piece: piece.id,
747
+ label: piece.label,
748
+ ...outcomeOf(source, piece, made.get(piece.id) ?? [], from.some((entry) => MECHANICS.includes(entry.kind)), options.finished === true),
749
+ madeInto: [...made.get(piece.id) ?? [], ...labels]
750
+ };
802
751
  });
803
- const byId = new Map(result.locations.map((location) => [location.id, location]));
804
- const fileOf = (id) => join(dir, files.get(id) ?? id, LOCATION_FILE_NAME);
805
- for (const location of result.locations) {
806
- if (location.parent !== void 0 && !byId.has(location.parent)) result.problems.push({
807
- path: fileOf(location.id),
808
- message: `parent: "${location.parent}" is not a place of this world`
809
- });
810
- if (location.parent === location.id) result.problems.push({
811
- path: fileOf(location.id),
812
- message: "parent: a place cannot be in itself"
813
- });
814
- location.exits.forEach((exit, index) => {
815
- if (!byId.has(exit.to)) result.problems.push({
816
- path: fileOf(location.id),
817
- message: `exits[${index}].to: "${exit.to}" is not a place of this world`
818
- });
819
- if (exit.to === location.id) result.problems.push({
820
- path: fileOf(location.id),
821
- message: `exits[${index}].to: an exit must lead to another place`
822
- });
823
- });
824
- const seen = /* @__PURE__ */ new Set();
825
- for (let up = location.parent === location.id ? void 0 : location.parent; up !== void 0 && byId.has(up); up = byId.get(up)?.parent) {
826
- if (up === location.id || seen.has(up)) {
827
- result.problems.push({
828
- path: fileOf(location.id),
829
- message: "parent: the places contain each other in a circle"
830
- });
831
- break;
832
- }
833
- seen.add(up);
834
- }
835
- }
836
- return result;
837
752
  }
838
- /** The places in an order where each comes after the one it is in. */
839
- function parentsFirst(locations) {
840
- const ordered = [];
841
- const placed = /* @__PURE__ */ new Set();
842
- const byId = new Map(locations.map((location) => [location.id, location]));
843
- const place = (location) => {
844
- if (placed.has(location.id)) return;
845
- placed.add(location.id);
846
- const parent = location.parent === void 0 ? void 0 : byId.get(location.parent);
847
- if (parent !== void 0) place(parent);
848
- ordered.push(location);
849
- };
850
- for (const location of locations) place(location);
851
- return ordered;
753
+ const outcomeCounts = (outcomes) => Object.fromEntries(OUTCOMES.map((outcome) => [outcome, outcomes.filter((entry) => entry.outcome === outcome).length]));
754
+ // src/host/import/card-tools.ts
755
+ /** The most of a piece one `card_read` returns; a long lorebook entry is read in turns. */
756
+ const READ_CHARS = 6e3;
757
+ const SNIPPET_CHARS = 240;
758
+ const DEFAULT_HITS = 8;
759
+ const MAX_HITS = 20;
760
+ const baseId = (id) => id.replace(/#\d+$/, "");
761
+ /** The folder inside `.import` where a newer version of the card waits to be applied to the world. */
762
+ const UPDATE_FOLDER = "update";
763
+ /** Everything the card holds, in the order the card has it. */
764
+ function cardPieces(card, choices) {
765
+ const read = new Set(itemise(card, choices).map((item) => baseId(item.id)));
766
+ const field = (id, label, text) => text.trim() === "" ? [] : [{
767
+ id,
768
+ label,
769
+ title: "",
770
+ keys: [],
771
+ text,
772
+ used: read.has(id)
773
+ }];
774
+ return [
775
+ ...field("field:description", "description", card.description),
776
+ ...field("field:personality", "personality", card.personality),
777
+ ...field("field:scenario", "scenario", card.scenario),
778
+ ...field("field:example", "example messages", card.messageExample),
779
+ ...field("field:first-message", "first message", card.firstMessage),
780
+ ...card.alternateGreetings.flatMap((text, index) => field(`field:greeting-${index + 1}`, `alternate greeting ${index + 1}`, text)),
781
+ ...field("field:creator-notes", "creator's notes", card.creatorNotes),
782
+ ...field("field:system-prompt", "system prompt", card.systemPrompt),
783
+ ...field("field:post-history", "post-history instructions", card.postHistoryInstructions),
784
+ ...(card.book?.entries ?? []).filter((entry) => entry.content.trim() !== "").map((entry) => ({
785
+ id: entry.id,
786
+ label: entry.title === "" ? entry.id : `entry “${entry.title}”`,
787
+ title: entry.title,
788
+ keys: entry.keys,
789
+ text: entry.content,
790
+ used: read.has(entry.id),
791
+ enabled: entry.enabled
792
+ }))
793
+ ];
852
794
  }
853
- // src/host/triggers/load.ts
854
- const TRIGGERS_FILE_NAME = "triggers.json";
855
- /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
856
- function parseTriggersFile(text) {
857
- let data;
795
+ async function optional(file) {
858
796
  try {
859
- data = JSON.parse(text.replace(/^/, ""));
797
+ return JSON.parse(await readFile(file, "utf8"));
860
798
  } catch (error) {
861
- return {
862
- ok: false,
863
- issues: [{
864
- path: "",
865
- message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
866
- }]
867
- };
799
+ if (error.code === "ENOENT") return void 0;
800
+ throw error;
868
801
  }
869
- if (!Array.isArray(data)) return {
870
- ok: false,
871
- issues: [{
872
- path: "",
873
- message: "expected a list of triggers"
874
- }]
875
- };
876
- const issues = [];
877
- const definitions = [];
878
- data.forEach((entry, index) => {
879
- const parsed = readTriggerDefinition(entry, `[${index}]`);
880
- if ("problems" in parsed) for (const problem of parsed.problems) {
881
- const split = problem.indexOf(": ");
882
- issues.push({
883
- path: split < 0 ? `[${index}]` : problem.slice(0, split),
884
- message: split < 0 ? problem : problem.slice(split + 2)
885
- });
886
- }
887
- else definitions.push(parsed.definition);
888
- });
889
- const keys = definitions.map((definition) => definition.key);
890
- keys.forEach((key, index) => {
891
- if (keys.indexOf(key) !== index) issues.push({
892
- path: "",
893
- message: `the trigger "${key}" is defined twice`
894
- });
895
- });
896
- return issues.length > 0 ? {
897
- ok: false,
898
- issues
899
- } : {
900
- ok: true,
901
- value: definitions
902
- };
903
802
  }
904
- /** Read the world's triggers: an optional `<world>/triggers.json`. A world with none only has what the story makes. */
905
- async function loadTriggers(worldDir) {
906
- const result = {
907
- triggers: [],
908
- problems: []
909
- };
910
- const file = join(worldDir, TRIGGERS_FILE_NAME);
803
+ /** 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. */
804
+ async function readSource(directory, withRecords, version = "current") {
805
+ const folder = join(directory, IMPORT_FOLDER);
806
+ let read;
911
807
  try {
912
- result.triggers = await readDocument$1(file, parseTriggersFile, result.problems) ?? [];
808
+ read = await readImportFolder(version === "new" ? join(folder, UPDATE_FOLDER) : folder);
913
809
  } catch (error) {
914
- if (error.code !== "ENOENT") result.problems.push({
915
- path: file,
916
- message: errorMessage(error)
917
- });
810
+ 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");
811
+ throw error;
918
812
  }
919
- return result;
920
- }
921
- // src/host/sessions/populate.ts
922
- /** What is wrong with how the characters stand towards each other, found before anything is created. */
923
- function relationshipProblems(characters) {
924
- const ids = new Set(characters.map((character) => character.id));
925
- return characters.flatMap((character) => (character.relationships ?? []).flatMap((relation) => {
926
- if (relation.to === character.id) return [`${character.id}: relationships: a character has no relationship with itself`];
927
- return ids.has(relation.to) ? [] : [`${character.id}: relationships: "${relation.to}" is not a character of this world`];
928
- }));
929
- }
930
- function factionProblems(factions, characters) {
931
- const factionIds = new Set(factions.map((faction) => faction.id));
932
- const characterIds = new Set(characters.map((character) => character.id));
933
- return factions.flatMap((faction) => [...faction.members.flatMap((member) => characterIds.has(member.character) ? [] : [`${faction.id}: members: "${member.character}" is not a character of this world`]), ...faction.relationships.flatMap((relation) => {
934
- if (relation.to.kind === "faction" && relation.to.id === faction.id) return [`${faction.id}: relationships: a faction has no relationship with itself`];
935
- return (relation.to.kind === "character" ? characterIds : factionIds).has(relation.to.id) ? [] : [`${faction.id}: relationships: "${relation.to.id}" is not a ${relation.to.kind} of this world`];
936
- })]);
937
- }
938
- /** What is wrong with the places, things and directed ways characters are authored to know. */
939
- function knowledgeProblems(characters, locations, items, lore = []) {
940
- const places = new Map(locations.map((location) => [location.id, location]));
941
- const things = new Set(items.map((item) => item.id));
942
- const loreIds = new Set(lore.map((entry) => entry.id));
943
- const wayExists = (from, to) => places.get(from)?.exits.some((exit) => exit.to === to) === true || places.get(to)?.exits.some((exit) => exit.to === from && !exit.oneWay) === true;
944
- return characters.flatMap((character) => {
945
- const prefix = `${character.id}: knowledge`;
946
- const knowledge = character.knowledge;
947
- if (knowledge === void 0) return [];
948
- return [
949
- ...knowledge.locations.flatMap((key) => places.has(key) ? [] : [`${prefix}.locations: "${key}" is not a place of this world`]),
950
- ...knowledge.items.flatMap((key) => things.has(key) ? [] : [`${prefix}.items: "${key}" is not an item of this world`]),
951
- ...knowledge.exits.flatMap(({ from, to }) => wayExists(from, to) ? [] : [`${prefix}.exits: there is no exit from "${from}" to "${to}"`]),
952
- ...(knowledge.lore ?? []).flatMap((key) => loreIds.has(key) ? [] : [`${prefix}.lore: "${key}" is not lore of this world`])
953
- ];
954
- });
955
- }
956
- /** Whether a world's characters include the one a lore entry names by id, name or alias. */
957
- function knowsCharacter(characters, reference) {
958
- const key = reference.normalize("NFKC").toLowerCase();
959
- return characters.some((character) => character.id === reference || [character.name, ...character.aliases].some((name) => name.normalize("NFKC").toLowerCase() === key));
960
- }
961
- function loreProblems(lore, world) {
962
- const ids = {
963
- character: new Set(world.characters.map((x) => x.id)),
964
- faction: new Set(world.factions.map((x) => x.id)),
965
- location: new Set(world.locations.map((x) => x.id)),
966
- item: new Set(world.items.map((x) => x.id)),
967
- lore: new Set(lore.map((x) => x.id))
813
+ const records = withRecords && version === "current" ? {
814
+ classified: await optional(join(folder, "classification.json")),
815
+ roster: await optional(join(folder, "roster.json")),
816
+ report: await optional(join(folder, "report.json"))
817
+ } : {};
818
+ return {
819
+ card: read.card,
820
+ choices: read.choices,
821
+ pieces: cardPieces(read.card, read.choices),
822
+ records
968
823
  };
969
- return lore.flatMap((entry) => [
970
- ...entry.subjects.flatMap((subject) => ids[subject.kind].has(subject.id) ? [] : [`${entry.id}: subjects: "${subject.id}" is not a ${subject.kind} of this world`]),
971
- ...entry.knownBy.flatMap((reference) => knowsCharacter(world.characters, reference) ? [] : [`${entry.id}: known_by: "${reference}" is not a character of this world`]),
972
- ...entry.related.flatMap((id) => id === entry.id ? [`${entry.id}: related: lore cannot relate to itself`] : ids.lore.has(id) ? [] : [`${entry.id}: related: "${id}" is not lore of this world`])
973
- ]);
974
824
  }
975
- /** `turn` is when the characters that know an entry learned it: 0 at the start, the story's turn when a lorebook is added later. */
976
- function populateLore(session, definitions, turn = 0) {
977
- for (const entry of definitions) session.lore.add({
978
- sourceId: entry.id,
979
- title: entry.title,
980
- kind: entry.kind,
981
- scope: entry.scope,
982
- summary: entry.summary,
983
- body: entry.body,
984
- ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
985
- ...entry.endsAt === void 0 ? {} : { endsAt: entry.endsAt },
986
- subjects: [],
987
- related: [],
988
- sources: entry.sources
989
- });
990
- const subject = (wanted) => ({
991
- kind: wanted.kind,
992
- id: wanted.kind === "character" ? session.characters.getBySourceId(wanted.id).id : wanted.kind === "faction" ? session.factions.getBySourceId(wanted.id).id : wanted.kind === "location" ? session.locations.getBySourceId(wanted.id).id : wanted.kind === "item" ? session.items.getBySourceId(wanted.id).id : session.lore.getBySourceId(wanted.id).id
993
- });
994
- for (const entry of definitions) session.lore.update(session.lore.getBySourceId(entry.id).id, {
995
- subjects: entry.subjects.map(subject),
996
- related: entry.related.map((id) => session.lore.getBySourceId(id).id)
997
- });
998
- for (const entry of definitions) {
999
- const lore = session.lore.getBySourceId(entry.id);
1000
- for (const reference of entry.knownBy) {
1001
- const knower = session.characters.getBySourceId(reference) ?? session.characters.findByName(reference)[0];
1002
- if (knower !== void 0) session.knowledge.learn(knower.id, "lore", lore.id, turn);
1003
- }
1004
- }
825
+ const rolesOf = (classified, id) => {
826
+ if (classified === void 0) return [];
827
+ return [...new Set(Object.entries(classified).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
828
+ };
829
+ function snippet$1(text, at, length) {
830
+ const start = Math.max(0, at - Math.floor((SNIPPET_CHARS - length) / 2));
831
+ const end = Math.min(text.length, start + SNIPPET_CHARS);
832
+ return `${start > 0 ? "…" : ""}${text.slice(start, end).replace(/\s+/g, " ")}${end < text.length ? "…" : ""}`;
1005
833
  }
1006
- /** What is wrong with where the characters start, found before anything is created. */
1007
- function startingPlaceProblems(characters, locations) {
1008
- const byId = new Map(locations.map((location) => [location.id, location]));
1009
- return characters.flatMap((character) => {
1010
- const place = character.start.place;
1011
- if (place === void 0) return [];
1012
- const location = byId.get(place.location);
1013
- if (location === void 0) return [`${character.id}: start.location "${place.location}" is not a place of this world`];
1014
- if (place.feature !== void 0 && !location.features.some((feature) => feature.key === place.feature)) return [`${character.id}: start.feature "${place.feature}" is not a feature of ${location.name} (it has: ${location.features.map((feature) => feature.key).join(", ") || "none"})`];
1015
- return [];
1016
- });
1017
- }
1018
- /** Declare what the world tracks and give everything the values it starts with. */
1019
- function populateVariables(session, defs, world) {
1020
- for (const def of defs) session.variables.define(def);
1021
- const give = (kind, id, values) => {
1022
- for (const [key, value] of Object.entries(values ?? {})) session.variables.set(key, kind, id, { value }, 0);
834
+ function searchPieces(pieces, query, limit) {
835
+ const phrase = query.trim().toLowerCase();
836
+ if (phrase === "") return [];
837
+ const words = [...new Set(phrase.split(/[\s,;,、]+/).filter((word) => word.length >= (/^[\x00-\x7f]+$/.test(word) ? 3 : 2)))];
838
+ const count = (text, needle) => {
839
+ let n = 0;
840
+ let first = -1;
841
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
842
+ n += 1;
843
+ if (first < 0) first = at;
844
+ }
845
+ return {
846
+ n,
847
+ first
848
+ };
1023
849
  };
1024
- for (const entry of world.characters) give("character", session.characters.getBySourceId(entry.id).id, entry.variables);
1025
- for (const entry of world.items) give("item", session.items.getBySourceId(entry.id).id, entry.variables);
1026
- for (const entry of world.locations) give("location", session.locations.getBySourceId(entry.id).id, entry.variables);
1027
- give("world", 0, world.values);
1028
- }
1029
- /** What is wrong with the days characters are given, found before anything is created: places that are not in the world. */
1030
- function routineProblems(characters, locations, calendar) {
1031
- calendar ??= {
1032
- hemisphere: "north",
1033
- holidays: []
850
+ const look = (text) => {
851
+ const lowered = text.toLowerCase();
852
+ const whole = count(lowered, phrase);
853
+ if (whole.n > 0) return {
854
+ matches: whole.n,
855
+ score: whole.n * 4 + 100,
856
+ at: whole.first,
857
+ length: phrase.length
858
+ };
859
+ const found = words.map((word) => ({
860
+ word,
861
+ ...count(lowered, word)
862
+ })).filter((entry) => entry.n > 0);
863
+ if (found.length === 0) return void 0;
864
+ const best = found.reduce((a, b) => a.first <= b.first ? a : b, found[0]);
865
+ return {
866
+ matches: found.reduce((sum, entry) => sum + entry.n, 0),
867
+ score: found.length * 10 + found.reduce((sum, entry) => sum + entry.n, 0),
868
+ at: best.first,
869
+ length: best.word.length
870
+ };
1034
871
  };
1035
- const byId = new Map(locations.map((location) => [location.id, location]));
1036
- const holidays = new Set(calendar.holidays.map((holiday) => holiday.id));
1037
- return characters.flatMap((character) => (character.routine ?? []).flatMap((window, index) => {
1038
- const days = dayTokenProblems(window.on ?? [], `${character.id}: routine[${index}].on`, holidays);
1039
- if (days.length > 0) return days;
1040
- if (window.location === void 0) return [];
1041
- const location = byId.get(window.location);
1042
- if (location === void 0) return [`${character.id}: routine[${index}].location "${window.location}" is not a place of this world`];
1043
- if (window.feature !== void 0 && !location.features.some((feature) => feature.key === window.feature)) return [`${character.id}: routine[${index}].feature "${window.feature}" is not a feature of ${location.name}`];
1044
- return [];
872
+ return pieces.flatMap((piece) => {
873
+ const inText = look(piece.text);
874
+ if (inText !== void 0) return [{
875
+ piece,
876
+ in: "text",
877
+ matches: inText.matches,
878
+ score: inText.score,
879
+ snippet: snippet$1(piece.text, inText.at, inText.length)
880
+ }];
881
+ const head = [piece.title, ...piece.keys].filter((part) => part !== "").join(" · ");
882
+ const inHead = look(head);
883
+ return inHead === void 0 ? [] : [{
884
+ piece,
885
+ in: "title or keys",
886
+ matches: inHead.matches,
887
+ score: inHead.score - 50,
888
+ snippet: `${piece.title === "" ? "" : `title: ${piece.title}`}${piece.keys.length === 0 ? "" : `${piece.title === "" ? "" : "; "}keys: ${piece.keys.join(", ")}`}`
889
+ }];
890
+ }).sort((a, b) => b.score - a.score).slice(0, limit).map(({ piece, matches, in: where, snippet: text }) => ({
891
+ piece,
892
+ matches,
893
+ in: where,
894
+ snippet: text
1045
895
  }));
1046
896
  }
1047
- /** Keeps the checks of the world with the story: what its game master rolls and how the dice are read. */
1048
- function populateDice(session, checks) {
1049
- for (const check of checks) session.dice.define(check);
1050
- }
1051
- /** Keeps the world's calendar with the story, for the days a routine or a trigger waits for. */
1052
- function populateCalendar(session, calendar) {
1053
- if (calendar.holidays.length > 0 || calendar.hemisphere !== "north") writeCalendar(session.metadata, calendar);
1054
- }
1055
- /** Gives each character its recurring day, with the places by their ids in the world. */
1056
- function populateRoutines(session, characters) {
1057
- for (const { id, routine } of characters) {
1058
- if (routine === void 0 || routine.length === 0) continue;
1059
- session.routines.replace(session.characters.getBySourceId(id).id, routine.map((window) => ({
1060
- days: window.days.map((day) => WEEKDAY_NAMES.indexOf(day)),
1061
- on: window.on ?? [],
1062
- start: parseTimeOfDay(window.from),
1063
- end: parseTimeOfDay(window.to),
1064
- activity: window.activity,
1065
- interruptible: window.interruptible,
1066
- ...window.sleep === true ? { sleep: true } : {},
1067
- ...window.location === void 0 ? {} : { locationId: session.locations.getBySourceId(window.location).id },
1068
- ...window.feature === void 0 ? {} : { featureKey: window.feature },
1069
- ...window.position === void 0 ? {} : { position: window.position }
1070
- })));
1071
- }
1072
- }
1073
- /** Put a world's places into a new session: each inside the one it belongs to, with the ways between them (both ways unless the file says one way). */
1074
- function populateLocations(session, locations) {
1075
- const ordered = parentsFirst(locations);
1076
- for (const { id, name, description, parent, features, visualIdentity } of ordered) {
1077
- const parentId = parent === void 0 ? void 0 : session.locations.getBySourceId(parent)?.id;
1078
- const stored = session.locations.add({
1079
- sourceId: id,
1080
- name,
1081
- description,
1082
- features,
1083
- ...parentId === void 0 ? {} : { parentId }
1084
- });
1085
- if (visualIdentity !== void 0) session.visualIdentities.set("location", stored.id, visualIdentity);
1086
- }
1087
- for (const location of ordered) {
1088
- const from = session.locations.getBySourceId(location.id);
1089
- for (const exit of location.exits) {
1090
- const to = session.locations.getBySourceId(exit.to);
1091
- const shared = {
1092
- ...exit.travelSeconds === void 0 ? {} : { travelSeconds: exit.travelSeconds },
1093
- state: exit.state,
1094
- note: exit.note
1095
- };
1096
- if (session.locations.getExit(from.id, to.id) === void 0) session.locations.addExit({
1097
- fromId: from.id,
1098
- toId: to.id,
1099
- description: exit.description,
1100
- ...shared
1101
- });
1102
- if (!exit.oneWay && session.locations.getExit(to.id, from.id) === void 0) session.locations.addExit({
1103
- fromId: to.id,
1104
- toId: from.id,
1105
- description: exit.backDescription ?? exit.description,
1106
- ...shared
1107
- });
1108
- }
1109
- }
1110
- }
897
+ const versionParameter = {
898
+ type: "string",
899
+ enum: ["current", "new"],
900
+ 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."
901
+ };
902
+ const output$1 = {
903
+ schema: { type: "json" },
904
+ render: (_args, value) => [{
905
+ type: "text",
906
+ text: JSON.stringify(value, null, 1)
907
+ }]
908
+ };
909
+ const json$1 = (value) => JSON.parse(JSON.stringify(value));
910
+ const idOf = (exec) => {
911
+ const chat = exec.agent?.session.id;
912
+ const world = chat === void 0 ? void 0 : authoredWorldOf(chat);
913
+ if (world === void 0) throw new Error("this tool is available only in a world authoring chat");
914
+ return world;
915
+ };
1111
916
  /**
1112
- * Put a world's cast into a new session: each character with the state it
1113
- * starts in and its intents. The player controls the character whose world id
1114
- * is `playerId`; the agent controls everyone else.
917
+ * 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.
918
+ * `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.
1115
919
  */
1116
- function populateCharacters(session, characters, playerId) {
1117
- for (const { id, start, relationships: _relationships, knowledge: _knowledge, routine: _routine, visualIdentity, ...identity } of characters) {
1118
- const character = session.characters.add({
1119
- ...identity,
1120
- sourceId: id,
1121
- control: id === playerId ? "player" : "agent"
1122
- });
1123
- if (visualIdentity !== void 0) session.visualIdentities.set("character", character.id, visualIdentity);
1124
- const { intents, place, emotion, ...state } = start;
1125
- session.characterStates.create(character.id, state);
1126
- if (emotion !== void 0) for (const axis of [
1127
- "valence",
1128
- "arousal",
1129
- "dominance"
1130
- ]) session.variables.set(axis, "character", character.id, {
1131
- value: emotion.immediate[axis],
1132
- baseline: emotion.baseline[axis]
1133
- }, 0);
1134
- for (const intent of intents) session.intents.add(character.id, intent);
1135
- if (place !== void 0) {
1136
- const location = session.locations.getBySourceId(place.location);
1137
- session.placements.place("character", character.id, {
1138
- locationId: location.id,
1139
- ...place.position === void 0 ? {} : { position: place.position },
1140
- ...place.feature === void 0 ? {} : { featureKey: place.feature }
1141
- });
1142
- }
1143
- }
1144
- for (const { id, relationships } of characters) {
1145
- const from = session.characters.getBySourceId(id);
1146
- for (const relation of relationships ?? []) session.relationships.upsert(from.id, session.characters.getBySourceId(relation.to).id, {
1147
- label: relation.label,
1148
- summary: relation.summary,
1149
- familiarity: relation.familiarity,
1150
- trust: relation.trust,
1151
- affinity: relation.affinity,
1152
- tension: relation.tension
1153
- }, 0);
1154
- }
1155
- }
1156
- function populateFactions(session, factions) {
1157
- for (const definition of factions) {
1158
- const faction = session.factions.add({
1159
- sourceId: definition.id,
1160
- name: definition.name,
1161
- aliases: definition.aliases,
1162
- summary: definition.summary,
1163
- description: definition.description,
1164
- values: definition.values,
1165
- structure: definition.structure
1166
- });
1167
- session.factionStates.create(faction.id, definition.start);
1168
- for (const goal of definition.start.goals) session.factionIntents.add(faction.id, goal);
1169
- }
1170
- for (const definition of factions) {
1171
- const faction = session.factions.getBySourceId(definition.id);
1172
- for (const member of definition.members) {
1173
- const character = session.characters.getBySourceId(member.character);
1174
- session.factionMemberships.upsert(faction.id, character.id, member, 0);
1175
- if (session.factionRelationships.get("character", character.id, "faction", faction.id) === void 0) session.factionRelationships.upsert("character", character.id, "faction", faction.id, {
1176
- label: member.role || "member",
1177
- familiarity: 1
1178
- }, 0);
1179
- }
1180
- for (const relation of definition.relationships) {
1181
- const target = relation.to.kind === "character" ? session.characters.getBySourceId(relation.to.id) : session.factions.getBySourceId(relation.to.id);
1182
- session.factionRelationships.upsert("faction", faction.id, relation.to.kind, target.id, relation, 0);
1183
- }
1184
- }
1185
- }
1186
- /** Give each character its authored knowledge, plus what is visible where it starts. */
1187
- function populateKnowledge(session, characters) {
1188
- for (const definition of characters) {
1189
- const character = session.characters.getBySourceId(definition.id);
1190
- for (const key of definition.knowledge?.locations ?? []) session.knowledge.learn(character.id, "location", session.locations.getBySourceId(key).id, 0);
1191
- for (const key of definition.knowledge?.items ?? []) session.knowledge.learn(character.id, "item", session.items.getBySourceId(key).id, 0);
1192
- for (const wanted of definition.knowledge?.exits ?? []) {
1193
- const exit = session.locations.getExit(session.locations.getBySourceId(wanted.from).id, session.locations.getBySourceId(wanted.to).id);
1194
- session.knowledge.learn(character.id, "exit", exit.id, 0);
1195
- session.knowledge.learn(character.id, "location", exit.fromId, 0);
1196
- session.knowledge.learn(character.id, "location", exit.toId, 0);
1197
- }
1198
- for (const key of definition.knowledge?.lore ?? []) session.knowledge.learn(character.id, "lore", session.lore.getBySourceId(key).id, 0);
1199
- const placement = session.placements.get("character", character.id);
1200
- if (placement === void 0) continue;
1201
- session.knowledge.learn(character.id, "location", placement.locationId, 0, true);
1202
- for (const exit of session.locations.exitsFrom(placement.locationId)) {
1203
- session.knowledge.learn(character.id, "exit", exit.id, 0, true);
1204
- session.knowledge.learn(character.id, "location", exit.toId, 0);
1205
- }
1206
- for (const { item } of session.items.contents({
1207
- kind: "location",
1208
- id: placement.locationId
1209
- })) if (!item.hidden) session.knowledge.learn(character.id, "item", item.id, 0, true);
1210
- for (const { item } of session.items.contents({
1211
- kind: "character",
1212
- id: character.id
1213
- })) session.knowledge.learn(character.id, "item", item.id, 0, true);
1214
- for (const other of session.placements.at(placement.locationId, "character")) if (other.entityId !== character.id && session.relationships.get(character.id, other.entityId) === void 0) session.relationships.upsert(character.id, other.entityId, { label: "acquaintance" }, 0);
1215
- }
1216
- }
1217
- /**
1218
- * Put a world's slots and things into a new session, each where it starts, with what opens each lock. Containers come
1219
- * before what is in them; what opens an exit is set for both directions of it.
1220
- */
1221
- function populateItems(session, items, slots, locations) {
1222
- for (const slot of slots) session.slots.upsert(slot);
1223
- const made = /* @__PURE__ */ new Map();
1224
- for (const definition of containersFirst(items)) {
1225
- const { start } = definition;
1226
- const holder = start.kind === "location" ? {
1227
- kind: "location",
1228
- locationId: session.locations.getBySourceId(start.location).id,
1229
- ...start.position === void 0 ? {} : { position: start.position },
1230
- ...start.feature === void 0 ? {} : { featureKey: start.feature }
1231
- } : start.kind === "held" ? {
1232
- kind: "character",
1233
- characterId: session.characters.getBySourceId(start.character).id,
1234
- mode: "held"
1235
- } : start.kind === "worn" ? {
1236
- kind: "character",
1237
- characterId: session.characters.getBySourceId(start.character).id,
1238
- mode: "worn",
1239
- slot: definition.wearable,
1240
- ...start.position === void 0 ? {} : { position: start.position }
1241
- } : {
1242
- kind: "item",
1243
- itemId: made.get(start.item),
1244
- ...start.position === void 0 ? {} : { position: start.position }
1245
- };
1246
- const item = session.items.add({
1247
- sourceId: definition.id,
1248
- name: definition.name,
1249
- description: definition.description,
1250
- quantity: definition.quantity,
1251
- unique: definition.unique,
1252
- quality: definition.quality,
1253
- notable: definition.notable,
1254
- hidden: definition.hidden,
1255
- ...definition.wearable === void 0 ? {} : { wearableSlot: definition.wearable },
1256
- ...definition.container === void 0 ? {} : { container: { state: definition.container.state } },
1257
- ...definition.owner === void 0 ? {} : { ownerId: session.characters.getBySourceId(definition.owner).id }
1258
- }, holder);
1259
- if (definition.visualIdentity !== void 0) session.visualIdentities.set("item", item.id, definition.visualIdentity);
1260
- made.set(definition.id, item.id);
1261
- }
1262
- for (const definition of items) if (definition.container !== void 0 && definition.container.openedBy.length > 0) session.items.setOpeners({
1263
- kind: "item",
1264
- id: made.get(definition.id)
1265
- }, definition.container.openedBy.map((key) => made.get(key)));
1266
- for (const place of locations) {
1267
- const from = session.locations.getBySourceId(place.id);
1268
- for (const exit of place.exits) {
1269
- if ((exit.openedBy ?? []).length === 0) continue;
1270
- const to = session.locations.getBySourceId(exit.to);
1271
- for (const [a, b] of [[from.id, to.id], [to.id, from.id]]) {
1272
- const way = session.locations.getExit(a, b);
1273
- if (way !== void 0) session.items.setOpeners({
1274
- kind: "exit",
1275
- id: way.id
1276
- }, exit.openedBy.map((key) => made.get(key)));
1277
- }
1278
- }
1279
- }
1280
- }
1281
- /** Starts the story's clock: at the wall clock when it follows it, and otherwise at the world's starting time (or now, when the world has none). */
1282
- function populateClock(session, settings, world, wall) {
1283
- const start = settings.mode === "real" ? wall : world?.startingTime ?? Math.floor(wall / MINUTE) * MINUTE;
1284
- session.clock.start(settings.mode, start);
1285
- }
1286
- /**
1287
- * Make the world's triggers, once everything they can name exists.
1288
- * @throws {Error} naming each trigger that names something the world does not have.
1289
- */
1290
- function populateTriggers(session, definitions) {
1291
- const keys = definitions.map((definition) => definition.key);
1292
- const problems = definitions.flatMap((definition) => triggerReferenceProblems(session, definition, keys));
1293
- if (problems.length > 0) throw new InvalidWorldError(`the triggers have ${problems.length} problem(s)`, problems.map((message) => ({
1294
- path: TRIGGERS_FILE_NAME,
1295
- message
1296
- })));
1297
- for (const definition of definitions) session.triggers.add(definition, "world", 0);
1298
- }
1299
- // src/host/worlds/scratch.ts
1300
- /**
1301
- * 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
1302
- * a store has; the search a session adds is not needed.
1303
- */
1304
- function withScratchStory(parts, use) {
1305
- const scratch = createSessionStore(":memory:", {
1306
- id: "scratch",
1307
- name: "scratch",
1308
- world: {
1309
- id: "scratch",
1310
- name: "scratch"
1311
- }
1312
- }, { vectors: false });
1313
- try {
1314
- const session = scratch;
1315
- if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
1316
- populateLocations(session, parts.locations);
1317
- populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
1318
- populateItems(session, parts.items, parts.slots, parts.locations);
1319
- populateVariables(session, parts.variables, {
1320
- characters: parts.characters,
1321
- items: parts.items,
1322
- locations: parts.locations,
1323
- values: void 0
1324
- });
1325
- return use(session);
1326
- } finally {
1327
- scratch.close();
1328
- }
1329
- }
1330
- // src/host/worlds/validated-world.ts
1331
- /**
1332
- * Reads everything a world's files hold and checks it all as a session start does: every file reads, and what refers to something refers to something that is there.
1333
- * @throws {InvalidWorldError} naming every problem of the first part of the world that has any.
1334
- */
1335
- async function loadValidatedWorld(world) {
1336
- const { characters, problems } = await loadCharacters(world.directory);
1337
- if (problems.length > 0) throw new InvalidWorldError(`the characters of "${world.summary.name}" have ${problems.length} problem(s)`, problems);
1338
- const { factions, problems: factionFileProblems } = await loadFactions(world.directory);
1339
- if (factionFileProblems.length > 0) throw new InvalidWorldError(`the factions of "${world.summary.name}" have ${factionFileProblems.length} problem(s)`, factionFileProblems);
1340
- const factionReferences = factionProblems(factions, characters);
1341
- if (factionReferences.length > 0) throw new InvalidWorldError(`the factions of "${world.summary.name}" have ${factionReferences.length} problem(s)`, factionReferences.map((message) => ({
1342
- path: world.directory,
1343
- message
1344
- })));
1345
- const { locations, problems: locationProblems } = await loadLocations(world.directory);
1346
- if (locationProblems.length > 0) throw new InvalidWorldError(`the places of "${world.summary.name}" have ${locationProblems.length} problem(s)`, locationProblems);
1347
- const placing = startingPlaceProblems(characters, locations);
1348
- if (placing.length > 0) throw new InvalidWorldError(`the starting places of "${world.summary.name}" have ${placing.length} problem(s)`, placing.map((message) => ({
1349
- path: world.directory,
1350
- message
1351
- })));
1352
- const { calendar, problems: calendarProblems } = await loadCalendar(world.directory);
1353
- if (calendarProblems.length > 0) throw new InvalidWorldError(`the calendar of "${world.summary.name}" has ${calendarProblems.length} problem(s)`, calendarProblems);
1354
- const dice = await loadDice(world.directory);
1355
- if (dice.problems.length > 0) throw new InvalidWorldError(`the dice checks of "${world.summary.name}" have ${dice.problems.length} problem(s)`, dice.problems);
1356
- const days = routineProblems(characters, locations, calendar);
1357
- if (days.length > 0) throw new InvalidWorldError(`the days of the characters of "${world.summary.name}" have ${days.length} problem(s)`, days.map((message) => ({
1358
- path: world.directory,
1359
- message
1360
- })));
1361
- const { items, slots, problems: itemProblems } = await loadItems(world.directory, {
1362
- characters: characters.map((character) => character.id),
1363
- locations
1364
- });
1365
- if (itemProblems.length > 0) throw new InvalidWorldError(`the items of "${world.summary.name}" have ${itemProblems.length} problem(s)`, itemProblems);
1366
- const authoredLore = await loadLore(world.directory);
1367
- if (authoredLore.problems.length > 0) throw new InvalidWorldError(`the lore of "${world.summary.name}" has ${authoredLore.problems.length} problem(s)`, authoredLore.problems);
1368
- const loreReferences = loreProblems(authoredLore.lore, {
1369
- characters,
1370
- factions,
1371
- locations,
1372
- items
1373
- });
1374
- if (loreReferences.length > 0) throw new InvalidWorldError(`the lore of "${world.summary.name}" has ${loreReferences.length} invalid reference(s)`, loreReferences.map((message) => ({
1375
- path: world.directory,
1376
- message
1377
- })));
1378
- const knowing = knowledgeProblems(characters, locations, items, authoredLore.lore);
1379
- if (knowing.length > 0) throw new InvalidWorldError(`the starting knowledge of "${world.summary.name}" has ${knowing.length} problem(s)`, knowing.map((message) => ({
1380
- path: world.directory,
1381
- message
1382
- })));
1383
- const declared = await loadVariables(world.directory);
1384
- if (declared.problems.length > 0) throw new InvalidWorldError(`the variables of "${world.summary.name}" have ${declared.problems.length} problem(s)`, declared.problems);
1385
- const commandFile = await loadCommands(world.directory);
1386
- if (commandFile.problems.length > 0) throw new InvalidWorldError(`the commands of "${world.summary.name}" have ${commandFile.problems.length} problem(s)`, commandFile.problems);
1387
- const own = new Set(declared.defs.map((def) => def.key));
1388
- const clashing = commandFile.commands.filter((command) => own.has(commandVariable(command)));
1389
- if (clashing.length > 0) throw new InvalidWorldError(`the commands of "${world.summary.name}" have ${clashing.length} problem(s)`, clashing.map((command) => ({
1390
- path: world.directory,
1391
- message: `/${command.word} raises the flag ${commandVariable(command)}, which variables.json declares too: remove one`
1392
- })));
1393
- declared.defs = [...declared.defs, ...commandFile.commands.map(commandFlag)];
1394
- const tracking = variableProblems({
1395
- defs: declared.defs,
1396
- characters,
1397
- items,
1398
- locations,
1399
- values: world.variables
1400
- });
1401
- if (tracking.length > 0) throw new InvalidWorldError(`what "${world.summary.name}" tracks has ${tracking.length} problem(s)`, tracking.map((message) => ({
1402
- path: world.directory,
1403
- message
1404
- })));
1405
- const scripted = await loadTriggers(world.directory);
1406
- if (scripted.problems.length > 0) throw new InvalidWorldError(`the triggers of "${world.summary.name}" have ${scripted.problems.length} problem(s)`, scripted.problems);
1407
- const authoredPlots = await loadPlots(world.directory);
1408
- if (authoredPlots.problems.length > 0) throw new InvalidWorldError(`the plots of "${world.summary.name}" have ${authoredPlots.problems.length} problem(s)`, authoredPlots.problems);
1409
- const plotReferences = plotReferenceProblems(authoredPlots.plots, [
1410
- ...characters.map((entry) => entry.id),
1411
- ...factions.map((entry) => entry.id),
1412
- ...locations.map((entry) => entry.id),
1413
- ...items.map((entry) => entry.id),
1414
- ...authoredLore.lore.map((entry) => entry.id)
1415
- ]);
1416
- if (plotReferences.length > 0) throw new InvalidWorldError(`the plots of "${world.summary.name}" have ${plotReferences.length} invalid participant(s)`, plotReferences.map((message) => ({
1417
- path: world.directory,
1418
- message
1419
- })));
1420
- const related = relationshipProblems(characters);
1421
- if (related.length > 0) throw new InvalidWorldError(`the relationships of "${world.summary.name}" have ${related.length} problem(s)`, related.map((message) => ({
1422
- path: world.directory,
1423
- message
1424
- })));
1425
- withScratchStory({
1426
- characters,
1427
- locations,
1428
- items,
1429
- slots,
1430
- variables: declared.defs,
1431
- calendar
1432
- }, (story) => {
1433
- populateTriggers(story, scripted.triggers);
1434
- });
1435
- return {
1436
- characters,
1437
- factions,
1438
- locations,
1439
- items,
1440
- slots,
1441
- authoredLore,
1442
- declared,
1443
- scripted,
1444
- authoredPlots,
1445
- calendar,
1446
- checks: dice.checks,
1447
- commands: commandFile.commands
920
+ function cardTools(worlds, options = {}) {
921
+ const withRecords = options.records !== false;
922
+ const source = async (exec, version = "current") => {
923
+ const id = idOf(exec);
924
+ const record = await worlds.find(id);
925
+ if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
926
+ return await readSource(record.directory, withRecords, version);
1448
927
  };
1449
- }
1450
- // src/host/worlds/world-check.ts
1451
- /** The most problems listed at once: the rest are named by their number. */
1452
- const LISTED$1 = 40;
1453
- /**
1454
- * 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
1455
- * 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
1456
- * fixing those can show the next part's.
1457
- */
1458
- async function checkWorld(world) {
1459
- try {
1460
- await loadValidatedWorld(world);
1461
- return {
1462
- ok: true,
1463
- problems: [],
1464
- more: 0
1465
- };
1466
- } catch (error) {
1467
- if (!(error instanceof InvalidWorldError)) throw error;
1468
- const problems = error.problems.map((problem) => ({
1469
- where: relative(world.directory, problem.path).split(sep).join("/") || "(the world)",
1470
- message: problem.message
1471
- }));
1472
- return {
1473
- ok: false,
1474
- summary: error.message,
1475
- problems: problems.slice(0, LISTED$1),
1476
- more: Math.max(0, problems.length - LISTED$1)
1477
- };
1478
- }
1479
- }
1480
- // src/host/import/casting.ts
1481
- const CASTING_SCHEMA = {
1482
- type: "object",
1483
- properties: {
1484
- commands: {
1485
- type: "array",
1486
- items: {
1487
- type: "object",
1488
- properties: {
1489
- word: { type: "string" },
1490
- description: { type: "string" }
928
+ const versionOf = (value) => {
929
+ if (value === void 0 || value === "current") return "current";
930
+ if (value === "new") return "new";
931
+ throw new Error("version must be current or new");
932
+ };
933
+ const find = (pieces, id) => {
934
+ const found = pieces.find((piece) => piece.id === id);
935
+ if (found === void 0) throw new Error(`the card has no piece "${id}": use an id from card_overview or card_search`);
936
+ return found;
937
+ };
938
+ return [
939
+ defineTool({
940
+ name: "card_overview",
941
+ 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.",
942
+ parameters: {},
943
+ output: output$1,
944
+ isConcurrencySafe: () => true,
945
+ async execute(_args, exec) {
946
+ const { card, choices, pieces, records } = await source(exec);
947
+ const madeFrom = entitiesByPiece({
948
+ card,
949
+ choices,
950
+ pieces,
951
+ records
952
+ });
953
+ const made = (id) => madeFrom.get(id) ?? [];
954
+ const outcomes = withRecords ? pieceOutcomes({
955
+ card,
956
+ choices,
957
+ pieces,
958
+ records
959
+ }, madeFrom) : [];
960
+ return json$1({
961
+ card: {
962
+ name: card.name,
963
+ creator: card.creator,
964
+ version: card.characterVersion,
965
+ tags: card.tags,
966
+ format: card.sourceSpec,
967
+ ignoredScripts: card.ignored.scripts
968
+ },
969
+ ...withRecords ? { outcomes: outcomeCounts(outcomes) } : {},
970
+ pieces: pieces.map((piece) => ({
971
+ id: piece.id,
972
+ label: piece.label,
973
+ characters: piece.text.length,
974
+ readByTheImport: piece.used,
975
+ ...withRecords ? {
976
+ outcome: outcomes.find((entry) => entry.piece === piece.id)?.outcome,
977
+ because: outcomes.find((entry) => entry.piece === piece.id)?.because
978
+ } : {},
979
+ ...piece.enabled === void 0 ? {} : { switchedOnInCard: piece.enabled },
980
+ ...withRecords ? {
981
+ takenToBe: rolesOf(records.classified, piece.id),
982
+ madeInto: made(piece.id)
983
+ } : {}
984
+ })),
985
+ ...records.roster === void 0 ? {} : { imported: records.roster.map((entity) => ({
986
+ name: entity.name,
987
+ kind: entity.kind,
988
+ aliases: entity.aliases,
989
+ playedByThePlayer: entity.player
990
+ })) },
991
+ ...records.report === void 0 ? {} : {
992
+ importNotes: records.report.notes,
993
+ leftOut: records.report.leftOut
994
+ },
995
+ 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."
996
+ });
997
+ }
998
+ }),
999
+ defineTool({
1000
+ name: "card_search",
1001
+ 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.",
1002
+ parameters: {
1003
+ query: {
1004
+ type: "string",
1005
+ required: true,
1006
+ description: "A name or phrase to look for, in the card's own language."
1491
1007
  },
1492
- required: ["word", "description"],
1493
- additionalProperties: false
1008
+ version: versionParameter,
1009
+ limit: {
1010
+ type: "number",
1011
+ description: `How many pieces to return, at most ${MAX_HITS} (default ${DEFAULT_HITS}).`
1012
+ }
1013
+ },
1014
+ output: output$1,
1015
+ isConcurrencySafe: () => true,
1016
+ async execute(args, exec) {
1017
+ const { pieces } = await source(exec, versionOf(args.version));
1018
+ const limit = Math.min(MAX_HITS, Math.max(1, Math.floor(typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : DEFAULT_HITS)));
1019
+ const hits = searchPieces(pieces, args.query, limit);
1020
+ return json$1({
1021
+ query: args.query,
1022
+ found: hits.length,
1023
+ hits: hits.map(({ piece, matches, in: where, snippet: text }) => ({
1024
+ piece: piece.id,
1025
+ label: piece.label,
1026
+ matches,
1027
+ foundIn: where,
1028
+ snippet: text
1029
+ }))
1030
+ });
1494
1031
  }
1495
- },
1496
- mechanisms: {
1497
- type: "array",
1498
- items: {
1499
- type: "object",
1500
- properties: {
1501
- name: { type: "string" },
1502
- command: { type: "string" },
1503
- happens: { type: "string" },
1504
- need: {
1505
- type: "string",
1506
- enum: ["arrival", "introduction"]
1507
- },
1508
- text: { type: "string" },
1509
- options: {
1510
- type: "array",
1511
- items: { type: "string" }
1512
- }
1032
+ }),
1033
+ defineTool({
1034
+ name: "card_read",
1035
+ 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.`,
1036
+ parameters: {
1037
+ piece: {
1038
+ type: "string",
1039
+ required: true,
1040
+ description: "A piece id from card_overview, card_search or card_diff, such as field:description or entry:3."
1513
1041
  },
1514
- required: [
1515
- "name",
1516
- "command",
1517
- "happens",
1518
- "need",
1519
- "text",
1520
- "options"
1521
- ],
1522
- additionalProperties: false
1042
+ version: versionParameter,
1043
+ offset: {
1044
+ type: "number",
1045
+ description: "Where to start reading, in characters (default 0)."
1046
+ }
1047
+ },
1048
+ output: output$1,
1049
+ isConcurrencySafe: () => true,
1050
+ async execute(args, exec) {
1051
+ const { pieces } = await source(exec, versionOf(args.version));
1052
+ const piece = find(pieces, args.piece);
1053
+ const from = Math.min(piece.text.length, Math.max(0, Math.floor(typeof args.offset === "number" && Number.isFinite(args.offset) ? args.offset : 0)));
1054
+ const to = Math.min(piece.text.length, from + READ_CHARS);
1055
+ return json$1({
1056
+ piece: piece.id,
1057
+ label: piece.label,
1058
+ ...piece.keys.length === 0 ? {} : { keys: piece.keys },
1059
+ from,
1060
+ to,
1061
+ of: piece.text.length,
1062
+ ...to < piece.text.length ? { next: to } : {},
1063
+ text: piece.text.slice(from, to)
1064
+ });
1523
1065
  }
1524
- }
1525
- },
1526
- required: ["commands", "mechanisms"],
1527
- additionalProperties: false
1528
- };
1529
- /** A trigger key is ASCII: the name's own letters when it has any, else the mechanism's number. */
1530
- const asciiKey = (name, number) => {
1531
- const key = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40);
1532
- return key === "" ? `casting_${number}` : key;
1533
- };
1534
- const str = (value) => typeof value === "string" ? value.trim() : "";
1535
- const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null) : [];
1536
- /** The most of the card's casting passages one request reads. */
1537
- const BUDGET_CHARS = 14e3;
1538
- const MAX_MECHANISMS = 8;
1539
- /**
1540
- * The documents of `commands.json` and `triggers.json` an answer describes: a command raises the flag its trigger waits on, a happening is a statement the story is judged
1541
- * against, and the trigger has the world author make the person (a drawn option when the card gives a list). What does not read as a valid file is left out, with a note.
1542
- */
1543
- /** Whether the passages name `word` as something the player types: after a slash, or alone in brackets or quotes. A word that only turns up in the card's sentences is a topic, not a command. */
1544
- function namedAsCommand(word, passages) {
1545
- const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1546
- return new RegExp(`/${escaped}(?![\\p{L}\\p{N}_])|[「『【\\[“"'‘((]\\s*/?${escaped}\\s*[」』】\\]”"'’))]`, "iu").test(passages.join("\n"));
1066
+ }),
1067
+ defineTool({
1068
+ name: "card_origin",
1069
+ 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.",
1070
+ parameters: { name: {
1071
+ type: "string",
1072
+ required: true,
1073
+ description: "The name or an alias, as the world or the card has it."
1074
+ } },
1075
+ output: output$1,
1076
+ isConcurrencySafe: () => true,
1077
+ async execute(args, exec) {
1078
+ const { card, choices, pieces, records } = await source(exec);
1079
+ const entity = records.roster === void 0 ? void 0 : findEntity(records.roster, args.name);
1080
+ if (entity === void 0 || records.classified === void 0) return json$1({
1081
+ name: args.name,
1082
+ madeByTheImport: false,
1083
+ mentions: searchPieces(pieces, args.name, DEFAULT_HITS).map(({ piece, in: where, snippet: text }) => ({
1084
+ piece: piece.id,
1085
+ label: piece.label,
1086
+ foundIn: where,
1087
+ snippet: text
1088
+ }))
1089
+ });
1090
+ return json$1({
1091
+ name: entity.name,
1092
+ kind: entity.kind,
1093
+ aliases: entity.aliases,
1094
+ madeByTheImport: true,
1095
+ usedPieces: originOf(card, choices, pieces, records, entity.name).map((entry) => ({
1096
+ piece: entry.piece,
1097
+ label: entry.label,
1098
+ how: entry.how,
1099
+ takenToBe: rolesOf(records.classified, entry.piece)
1100
+ }))
1101
+ });
1102
+ }
1103
+ })
1104
+ ];
1547
1105
  }
1548
- function castingDocuments(answer, passages = []) {
1549
- const notes = [];
1550
- const keyed = objects(answer["commands"]).map((entry) => ({
1551
- word: str(entry["word"]).toLowerCase().replace(/^\//, ""),
1552
- description: str(entry["description"])
1553
- })).filter((entry) => entry.word !== "" && entry.description !== "" && namedAsCommand(entry.word, passages)).map((entry, index) => ({
1554
- ...entry,
1555
- key: /^[a-z][a-z0-9_]{0,29}$/.test(entry.word) ? entry.word : `word_${index + 1}`
1556
- }));
1557
- const parsedCommands = parseCommandsFile(JSON.stringify({ commands: keyed.map((entry) => ({
1558
- word: entry.word,
1559
- key: entry.key,
1560
- description: entry.description
1561
- })) }));
1562
- const usable = parsedCommands.ok ? parsedCommands.value : [];
1563
- if (!parsedCommands.ok) notes.push(`commands not carried: ${parsedCommands.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ")}`);
1564
- const taken = /* @__PURE__ */ new Set();
1565
- const triggers = [];
1566
- for (const mechanism of objects(answer["mechanisms"]).slice(0, MAX_MECHANISMS)) {
1567
- const name = str(mechanism["name"]);
1568
- const command = usable.find((entry) => entry.word === str(mechanism["command"]).toLowerCase());
1569
- const happens = str(mechanism["happens"]) || (command === void 0 && str(mechanism["command"]) !== "" ? str(mechanism["name"]) : "");
1570
- const need = mechanism["need"] === "introduction" ? "introduction" : "arrival";
1571
- const options = Array.isArray(mechanism["options"]) ? mechanism["options"].map(str).filter((option) => option !== "") : [];
1572
- let words = str(mechanism["text"]) || name;
1573
- if (name === "" || command === void 0 && happens === "") {
1574
- notes.push(`casting not carried: "${name || "unnamed"}" has no reason to start it`);
1575
- continue;
1576
- }
1577
- if (options.length > 0 && !words.includes("[draw]")) words = `${words} [draw]`;
1578
- if (options.length === 0) words = words.replaceAll("[draw]", "").trim();
1579
- const when = command === void 0 ? {
1580
- type: "judged",
1581
- text: happens
1582
- } : {
1583
- type: "variable",
1584
- variable: commandFlagKey(command),
1585
- op: COMPARISONS[0],
1586
- value: true
1587
- };
1588
- triggers.push({
1589
- key: uniqueKey(asciiKey(name, triggers.length + 1), taken),
1590
- name,
1591
- when,
1592
- repeat: true,
1593
- effects: [{
1594
- type: "beat",
1595
- dispatch: "author",
1596
- need,
1597
- text: words,
1598
- ...options.length === 0 ? {} : { draw: options }
1599
- }]
1106
+ /** For each piece of the card, the names of the characters, places and things the import made from it. */
1107
+ function entitiesByPiece(source) {
1108
+ const made = /* @__PURE__ */ new Map();
1109
+ 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]);
1110
+ return made;
1111
+ }
1112
+ /** 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. */
1113
+ function originOf(card, choices, pieces, records, name, items = itemise(card, choices)) {
1114
+ if (records.roster === void 0 || records.classified === void 0) return [];
1115
+ const entity = findEntity(records.roster, name);
1116
+ if (entity === void 0) return [];
1117
+ const names = [entity.name, ...entity.aliases].map(norm);
1118
+ const chosen = sourcesFor(entity, items, records.classified);
1119
+ const about = (id) => (records.classified?.[id]?.targets ?? []).some((target) => target.kind === entity.kind && names.includes(norm(target.name)));
1120
+ const seen = /* @__PURE__ */ new Set();
1121
+ return chosen.flatMap((item) => {
1122
+ const id = baseId(item.id);
1123
+ const piece = pieces.find((entry) => entry.id === id);
1124
+ if (piece === void 0 || seen.has(id)) return [];
1125
+ seen.add(id);
1126
+ return [{
1127
+ piece: id,
1128
+ label: piece.label,
1129
+ how: about(item.id) ? "about it" : "mentions it"
1130
+ }];
1131
+ });
1132
+ }
1133
+ // src/host/import/opening-parts.ts
1134
+ const SCHEMA = {
1135
+ type: "object",
1136
+ properties: { parts: {
1137
+ type: "array",
1138
+ items: {
1139
+ type: "object",
1140
+ properties: {
1141
+ kind: {
1142
+ type: "string",
1143
+ enum: ["narration", "speech"]
1144
+ },
1145
+ speaker: { type: "string" },
1146
+ text: { type: "string" }
1147
+ },
1148
+ required: [
1149
+ "kind",
1150
+ "speaker",
1151
+ "text"
1152
+ ],
1153
+ additionalProperties: false
1154
+ }
1155
+ } },
1156
+ required: ["parts"],
1157
+ additionalProperties: false
1158
+ };
1159
+ const MAX_SHOWN = 6e3;
1160
+ const QUOTES = /["'“”‘’「」『』«»„‟*_]/gu;
1161
+ /** The letters of a passage with quotation marks, emphasis marks, labels that name a speaker and all spacing taken out: what must be the same before and after splitting. */
1162
+ function lettersOf$1(text, speakers = []) {
1163
+ let rest = text;
1164
+ for (const name of speakers.flatMap((speaker) => [speaker.name, ...speaker.aliases])) rest = rest.replace(new RegExp(`(^|\\n)\\s*${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[::]`, "gu"), "$1");
1165
+ return rest.replace(QUOTES, "").replace(/\s+/gu, "");
1166
+ }
1167
+ /** Why an answer is not the passage split into parts; nothing when it is. */
1168
+ function splitProblem(source, parts, speakers) {
1169
+ if (parts.length === 0) return "the answer has no parts";
1170
+ const wanted = lettersOf$1(source, speakers);
1171
+ const given = lettersOf$1(partsText(parts));
1172
+ if (wanted === given) return void 0;
1173
+ let same = 0;
1174
+ while (same < wanted.length && same < given.length && wanted[same] === given[same]) same += 1;
1175
+ const around = (text) => `“${text.slice(Math.max(0, same - 8), same + 24)}”`;
1176
+ return `the parts do not hold exactly the words of the passage, in order: they agree up to ${around(wanted)} and then the passage goes on with “${wanted.slice(same, same + 24)}” where your parts have “${given.slice(same, same + 24)}”. Keep every sentence, narration between spoken lines included; change none, add none`;
1177
+ }
1178
+ /** The speaker a name (or id) names; the player's character and unknown names are nobody, so the part is narration. */
1179
+ function speakerOf(name, speakers, player) {
1180
+ const key = norm(name);
1181
+ if (key === "") return void 0;
1182
+ return speakers.find((speaker) => speaker.id !== player && [
1183
+ speaker.id,
1184
+ speaker.name,
1185
+ ...speaker.aliases
1186
+ ].some((label) => norm(label) === key));
1187
+ }
1188
+ /** The parts an answer describes, with a speaker that is not in the cast made narration. */
1189
+ function partsOf$1(answer, speakers, player) {
1190
+ const list = Array.isArray(answer.parts) ? answer.parts : [];
1191
+ const parts = [];
1192
+ for (const entry of list) {
1193
+ if (typeof entry !== "object" || entry === null) continue;
1194
+ const body = entry;
1195
+ const text = typeof body["text"] === "string" ? tidyQuotes(body["text"]) : "";
1196
+ if (text === "") continue;
1197
+ const speaker = (body["kind"] ?? body["type"]) === "narration" ? void 0 : speakerOf(typeof body["speaker"] === "string" ? body["speaker"] : "", speakers, player);
1198
+ parts.push(speaker === void 0 ? {
1199
+ type: "narration",
1200
+ text
1201
+ } : {
1202
+ type: "utterance",
1203
+ character: speaker.id,
1204
+ text
1600
1205
  });
1601
1206
  }
1602
- const parsedTriggers = parseTriggersFile(JSON.stringify(triggers));
1603
- if (!parsedTriggers.ok) {
1604
- notes.push(`casting not carried: ${parsedTriggers.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ")}`);
1605
- return {
1606
- commands: [],
1607
- triggers: [],
1608
- notes
1609
- };
1207
+ return parts;
1208
+ }
1209
+ const PAIRS = [
1210
+ ["“", "”"],
1211
+ ["‘", "’"],
1212
+ ["「", "」"],
1213
+ ["『", "』"],
1214
+ ["«", "»"],
1215
+ ["„", "“"]
1216
+ ];
1217
+ const count = (text, mark) => text.split(mark).length - 1;
1218
+ /**
1219
+ * A part's words without the quotation marks that belong to its surroundings: the marks around a whole quoted line, and a mark left at an edge by a cut that fell inside a quotation
1220
+ * (an opening mark with no closing one, a closing mark with no opening one). A balanced quotation inside the words stays.
1221
+ */
1222
+ function tidyQuotes(text) {
1223
+ let result = text.trim();
1224
+ for (const [open, close] of [...PAIRS, ["\"", "\""]]) {
1225
+ const inside = result.slice(1, -1);
1226
+ if (result.length > 1 && result.startsWith(open) && result.endsWith(close) && !inside.includes(open) && !inside.includes(close)) result = inside.trim();
1227
+ }
1228
+ result = result.replace(/^[”’」』»\s]+/u, "").replace(/[“‘「『«„\s]+$/u, "");
1229
+ for (const [open, close] of PAIRS) {
1230
+ if (result.startsWith(open) && count(result, open) > count(result, close)) result = result.slice(1).trim();
1231
+ if (result.endsWith(close) && count(result, close) > count(result, open)) result = result.slice(0, -1).trim();
1232
+ }
1233
+ if (count(result, "\"") % 2 === 1) result = (result.startsWith("\"") ? result.slice(1) : result.endsWith("\"") ? result.slice(0, -1) : result).trim();
1234
+ return result;
1235
+ }
1236
+ /** A stretch of the passage without the spacing and the quotation marks at its ends: an opening quote belongs to the line after it, a closing one to the line before. */
1237
+ const unquoted = (text) => text.replace(/^[\s"“”‘’「」『』«»„‟]+|[\s"“”‘’「」『』«»„‟]+$/gu, "");
1238
+ /**
1239
+ * Puts back, as narration, the words of the passage that no part holds (a sentence between two spoken lines that the model skipped), when every part can be found in the passage in order.
1240
+ * Nothing is invented: a part that is not in the passage as written leaves the answer as it is, for the check to refuse.
1241
+ */
1242
+ function mendParts(source, parts, speakers) {
1243
+ const mended = [];
1244
+ let at = 0;
1245
+ for (const part of parts) {
1246
+ const found = source.indexOf(part.text, at);
1247
+ if (found < 0) return [...parts];
1248
+ const gap = unquoted(source.slice(at, found));
1249
+ if (lettersOf$1(gap, speakers) !== "") mended.push({
1250
+ type: "narration",
1251
+ text: gap
1252
+ });
1253
+ mended.push(part);
1254
+ at = found + part.text.length;
1610
1255
  }
1611
- const used = new Set(triggers.flatMap((trigger) => trigger["when"]["variable"] === void 0 ? [] : [String(trigger["when"]["variable"])]));
1612
- return {
1613
- commands: usable.filter((command) => used.has(commandFlagKey(command))).map((command) => ({ ...command })),
1614
- triggers,
1615
- notes
1616
- };
1256
+ const tail = unquoted(source.slice(at));
1257
+ if (lettersOf$1(tail, speakers) !== "") mended.push({
1258
+ type: "narration",
1259
+ text: tail
1260
+ });
1261
+ return mended;
1617
1262
  }
1618
- /** Turns what the card says about making people up into the world's commands and the triggers that have the world author make them. */
1619
- async function extractCasting(ctx, card, passages) {
1620
- if (passages.length === 0) return {
1621
- commands: [],
1622
- triggers: [],
1623
- notes: []
1624
- };
1625
- ctx.say("turning the casting guidance into commands and triggers");
1263
+ /**
1264
+ * Decides whether an opening is pure narration (kept as plain text) or has characters speaking (split into parts), and splits it. With a decision model the closed question
1265
+ * "does anyone speak" is asked first and a sure answer settles it; otherwise, or when it is unsure, the language model answers both in one reply. With no model the
1266
+ * opening stays as it is. A split that does not hold exactly the passage's words is refused, and the opening then stays plain with a note: no text is lost or invented.
1267
+ */
1268
+ async function shapeOpening(ctx, passage, speakers, player) {
1269
+ const plain = { text: passage };
1270
+ if (ctx.noModel === true || passage.trim() === "" || speakers.every((speaker) => speaker.id === player)) return plain;
1271
+ if (ctx.decide !== void 0) try {
1272
+ const speech = (await ctx.decide({ passage: passage.slice(0, MAX_SHOWN) }, [{
1273
+ key: "speech",
1274
+ instructions: ctx.text("roleplay/decide-opening")
1275
+ }])).get("speech") ?? .5;
1276
+ const confidence = ctx.confidence ?? .7;
1277
+ if (speech <= noAt(confidence)) return plain;
1278
+ } catch {}
1626
1279
  try {
1627
1280
  const tr = trOf(ctx);
1628
- const prompt = `${tr("Card: {name}", { name: card.name })}\n\n${tr("Passages about making people up:")}\n\n${passages.join("\n\n---\n\n").slice(0, BUDGET_CHARS)}`;
1629
- return castingDocuments(await ctx.run({
1630
- persona: ctx.text("import/casting", { rules: ctx.text("import/common-rules") }),
1631
- maxTokens: 3e3,
1632
- prompt,
1633
- result: CASTING_SCHEMA,
1634
- check: (value) => {
1635
- const made = castingDocuments(value, passages);
1636
- return made.triggers.length === 0 && made.notes.length > 0 ? made.notes.join("; ") : void 0;
1637
- }
1638
- }), passages);
1281
+ const cast = speakers.filter((speaker) => speaker.id !== player).map((speaker) => `- ${speaker.name}`).join("\n");
1282
+ const parts = mendParts(passage, partsOf$1(await ctx.run({
1283
+ persona: ctx.text("import/opening"),
1284
+ maxTokens: Math.min(8e3, Math.max(1500, Math.ceil(passage.length / 2) + 600)),
1285
+ prompt: `${tr("Cast:")}\n${cast}\n\n${tr("Passage:")}\n${passage}`,
1286
+ result: SCHEMA,
1287
+ check: (value) => splitProblem(passage, mendParts(passage, partsOf$1(value, speakers, player), speakers), speakers)
1288
+ }), speakers, player), speakers);
1289
+ return parts.some((part) => part.type === "utterance") ? {
1290
+ text: partsText(parts),
1291
+ parts
1292
+ } : plain;
1639
1293
  } catch (error) {
1640
1294
  return {
1641
- commands: [],
1642
- triggers: [],
1643
- notes: [`the casting guidance was not turned into commands and triggers: ${error instanceof Error ? error.message : String(error)}`]
1295
+ ...plain,
1296
+ note: `the opening could not be split into parts, so it is kept as plain text: ${error instanceof Error ? error.message : String(error)}`
1644
1297
  };
1645
1298
  }
1646
1299
  }
1647
- // src/host/import/structure.ts
1648
- /** The most example lines the character keeps. */
1649
- const MAX_EXAMPLES = 8;
1650
- /** The summary is the start of the description: a sentence or two. */
1651
- const SUMMARY_CHARS = 280;
1652
- /** The lines of the example messages that the character speaks, as written; the markers of the tool that wrote them are taken out. */
1653
- function exampleLines(text, name) {
1654
- const lines = cleanText(text, name).split("\n").map((line) => line.trim()).filter((line) => line !== "");
1655
- const speaker = /^([^:\n]{1,100}):\s*(.*)$/;
1656
- if (!lines.some((line) => speaker.test(line))) return lines.slice(0, MAX_EXAMPLES);
1657
- const names = new Set([name, name.split(/\s+/)[0] ?? ""].map((part) => part.toLocaleLowerCase()));
1658
- return lines.flatMap((line) => {
1659
- const match = speaker.exec(line);
1660
- if (match?.[1] === void 0 || !names.has(match[1].trim().toLocaleLowerCase())) return [];
1661
- const utterance = match[2]?.trim();
1662
- return utterance === void 0 || utterance === "" ? [] : [utterance];
1663
- }).slice(0, MAX_EXAMPLES);
1300
+ // src/host/import/repair.ts
1301
+ const ENTITY_FILE = /^(characters|locations|factions|items|lore)\/[^/]+\/(character|location|faction|item|lore)\.json$/;
1302
+ /** Fields a document cannot do without, and fields that tie it to others: never dropped, whatever the problem says. */
1303
+ const KEPT = /* @__PURE__ */ new Set([
1304
+ "id",
1305
+ "name",
1306
+ "role",
1307
+ "kind",
1308
+ "tier",
1309
+ "from",
1310
+ "to",
1311
+ "parent",
1312
+ "summary"
1313
+ ]);
1314
+ const ABOUT_VALUE = /^(must be|is longer than|has more than|is not one of|must not|cannot be)/;
1315
+ const STEP = /([^.[\]]+)|\[(\d+)\]/g;
1316
+ const stepsOf = (field) => [...field.matchAll(STEP)].map((match) => match[2] === void 0 ? match[1] : Number(match[2]));
1317
+ /** Removes what `steps` names; false when it is not there. */
1318
+ function remove(root, steps) {
1319
+ let at = root;
1320
+ for (const step of steps.slice(0, -1)) {
1321
+ at = at?.[step];
1322
+ if (typeof at !== "object" || at === null) return void 0;
1323
+ }
1324
+ const last = steps.at(-1);
1325
+ if (typeof at !== "object" || at === null || !(last in at)) return void 0;
1326
+ const value = at[last];
1327
+ if (Array.isArray(at) && typeof last === "number") at.splice(last, 1);
1328
+ else delete at[last];
1329
+ return { value };
1664
1330
  }
1665
1331
  /**
1666
- * What a card holds, laid out without a model: the card's own character from its description, personality and examples, its lorebook entries as lore in its own words (for the game master only,
1667
- * as nothing has read what they say), and its instructions as the narration style, word for word. No place, faction, thing or other person is found: those take a reader.
1332
+ * Mends what the world check refused, one field at a time and only where that is safe: an optional field of an entity whose value cannot be used (wrong type, too long, not one of the
1333
+ * allowed words) is dropped. A missing required field, a name, an id or a link to another entity is never touched: those stay problems for a person or the assistant. Returns what was dropped, with the values.
1668
1334
  */
1669
- function structureOnly(card, items, _choices) {
1670
- const taken = /* @__PURE__ */ new Set();
1671
- const roster = [{
1672
- kind: "character",
1673
- key: uniqueKey(slug(card.name, "character"), taken),
1674
- name: card.name,
1675
- aliases: [],
1676
- player: false
1677
- }];
1678
- const target = [{
1679
- name: card.name,
1680
- kind: "character"
1681
- }];
1682
- const classified = {};
1683
- for (const item of items) if (item.id.startsWith("field:description") || item.id.startsWith("field:personality")) classified[item.id] = {
1684
- roles: ["character"],
1685
- targets: target
1686
- };
1687
- else if (item.id.startsWith("field:example")) classified[item.id] = {
1688
- roles: ["speech"],
1689
- targets: target
1690
- };
1691
- else if (item.id.startsWith("field:")) classified[item.id] = {
1692
- roles: ["scenario"],
1693
- targets: []
1694
- };
1695
- else classified[item.id] = {
1696
- roles: ["world"],
1697
- targets: []
1698
- };
1699
- const extracted = emptyExtracted();
1700
- const description = cleanText(card.description, card.name);
1701
- const built = characterDocument(roster[0], {
1702
- tier: "principal",
1703
- kind: "person",
1704
- summary: description.slice(0, SUMMARY_CHARS).trim(),
1705
- personality: cleanText(card.personality, card.name),
1706
- background: description,
1707
- speech: {
1708
- style: "",
1709
- examples: exampleLines(card.messageExample, card.name)
1335
+ async function repairFields(directory, problems) {
1336
+ const repairs = [];
1337
+ const byFile = /* @__PURE__ */ new Map();
1338
+ for (const problem of problems) {
1339
+ if (!ENTITY_FILE.test(problem.where)) continue;
1340
+ const split = problem.message.indexOf(": ");
1341
+ if (split < 0) continue;
1342
+ const field = problem.message.slice(0, split);
1343
+ const because = problem.message.slice(split + 2);
1344
+ if (!/^[\w.[\]]+$/.test(field) || !ABOUT_VALUE.test(because) || KEPT.has(stepsOf(field)[0])) continue;
1345
+ byFile.set(problem.where, [...byFile.get(problem.where) ?? [], {
1346
+ field,
1347
+ because
1348
+ }]);
1349
+ }
1350
+ for (const [file, fields] of byFile) {
1351
+ const document = JSON.parse(await readFile(join(directory, file), "utf8"));
1352
+ for (const { field, because } of fields.sort((a, b) => b.field.localeCompare(a.field, void 0, { numeric: true }))) {
1353
+ const dropped = remove(document, stepsOf(field));
1354
+ if (dropped !== void 0) repairs.push({
1355
+ file,
1356
+ field,
1357
+ value: dropped.value,
1358
+ because
1359
+ });
1710
1360
  }
1711
- }, roster);
1712
- extracted.characters.push(built.document);
1713
- extracted.notes.push(...built.notes);
1714
- for (const item of items.filter((entry) => entry.id.startsWith("entry:"))) for (const entry of loreDocuments(asWritten(item), roster, taken)) addLore(extracted.lore, {
1715
- ...entry.document,
1716
- scope: "listed"
1717
- });
1718
- const instructions = [card.systemPrompt, card.postHistoryInstructions].map((text) => cleanText(text, card.name)).filter((text) => text !== "");
1719
- if (instructions.length > 0) extracted.prompts.push({
1720
- id: "roleplay/style",
1721
- text: inert(instructions.join("\n\n"))
1361
+ if (repairs.some((repair) => repair.file === file)) await atomicWrite(join(directory, file), `${JSON.stringify(document, null, 2)}\n`);
1362
+ }
1363
+ return repairs;
1364
+ }
1365
+ // src/host/worlds/world-file-io.ts
1366
+ const queue = new SerialQueue();
1367
+ /**
1368
+ * Runs `work` after everything asked for the same folder before it has finished. The import, the editor and the assistant each read `world.json`, change a field and write it
1369
+ * back; run side by side, the last one to write would take back what the others changed.
1370
+ */
1371
+ function serialized(directory, work) {
1372
+ return queue.run(directory, work);
1373
+ }
1374
+ /** Changes `world.json` in place: read, `update`, written back in one step with the indentation the file had, nothing else moving in between. @returns the document as written. */
1375
+ function updateWorldFile(directory, update) {
1376
+ return serialized(directory, async () => {
1377
+ const file = join(directory, WORLD_FILE_NAME);
1378
+ const text = await readFile(file, "utf8");
1379
+ const document = JSON.parse(text.replace(/^/, ""));
1380
+ await update(document);
1381
+ await atomicWrite(file, JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") || text.trim() === "" ? "\n" : ""));
1382
+ return document;
1722
1383
  });
1723
- extracted.notes.push("imported without a model: only the card's own character, its lorebook and its instructions were carried over");
1724
- return {
1725
- classified,
1726
- roster,
1727
- extracted
1384
+ }
1385
+ // src/host/characters/load.ts
1386
+ const CHARACTERS_DIR = "characters";
1387
+ /**
1388
+ * Read the cast of one world: every subfolder of `<world>/characters/` that
1389
+ * holds a `character.json`. Ids must be unique; a repeated one is reported and
1390
+ * the later character skipped.
1391
+ */
1392
+ async function loadCharacters(worldDir) {
1393
+ const dir = join(worldDir, CHARACTERS_DIR);
1394
+ const result = {
1395
+ characters: [],
1396
+ problems: []
1728
1397
  };
1398
+ let folders;
1399
+ try {
1400
+ folders = await subfolders(dir);
1401
+ } catch (error) {
1402
+ result.problems.push({
1403
+ path: dir,
1404
+ message: errorMessage(error)
1405
+ });
1406
+ return result;
1407
+ }
1408
+ const folderById = /* @__PURE__ */ new Map();
1409
+ for (const folder of folders) {
1410
+ const file = join(dir, folder, CHARACTER_FILE_NAME);
1411
+ try {
1412
+ const character = await readDocument$1(file, (text) => parseCharacterFile(text, folder), result.problems);
1413
+ if (character === void 0) continue;
1414
+ const owner = folderById.get(character.id);
1415
+ if (owner !== void 0) {
1416
+ result.problems.push({
1417
+ path: file,
1418
+ message: `id "${character.id}" is already used by ${owner}`
1419
+ });
1420
+ continue;
1421
+ }
1422
+ folderById.set(character.id, folder);
1423
+ result.characters.push(character);
1424
+ } catch (error) {
1425
+ if (error.code !== "ENOENT") result.problems.push({
1426
+ path: file,
1427
+ message: errorMessage(error)
1428
+ });
1429
+ }
1430
+ }
1431
+ return result;
1729
1432
  }
1730
- // src/host/import/outcomes.ts
1433
+ // src/host/calendar/load.ts
1434
+ const CALENDAR_FILE_NAME = "calendar.json";
1435
+ const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
1731
1436
  /**
1732
- * What became of one piece of a card: `carried` is kept word for word (an opening), `converted` made characters, places, things or other entries of the world, `guidance`
1733
- * became instructions to the narrator, `read` was read for the world but nothing named came of it, `omitted` was left out on purpose, `awaiting` has not been looked at yet.
1437
+ * Read `calendar.json`: the holidays of the world and the hemisphere its seasons follow (docs/world-format.md). A holiday is told by days (`12-25`,
1438
+ * `09-21..09-22`, `nth:mon:1`, `season:winter`, a month, a weekday); it cannot name another holiday.
1734
1439
  */
1735
- const OUTCOMES = [
1736
- "carried",
1737
- "converted",
1738
- "guidance",
1739
- "read",
1740
- "omitted",
1741
- "awaiting"
1742
- ];
1743
- const rolesOf$1 = (source, id) => [...new Set(Object.entries(source.records.classified ?? {}).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
1744
- const MECHANICS = [
1745
- "variable",
1746
- "rules",
1747
- "command",
1748
- "trigger"
1749
- ];
1750
- function outcomeOf(source, piece, made, mechanics, finished) {
1751
- const { choices, card } = source;
1752
- const reported = source.records.report !== void 0 || finished;
1753
- if (piece.id === "field:creator-notes") return {
1754
- outcome: "omitted",
1755
- because: "notes to people, not part of the world"
1756
- };
1757
- if (piece.id === "field:first-message" || piece.id.startsWith("field:greeting-")) {
1758
- if (choices.opening.kind === "none") return {
1759
- outcome: "omitted",
1760
- because: "the person chose no opening"
1761
- };
1762
- return reported ? {
1763
- outcome: "carried",
1764
- because: "an opening of the world"
1765
- } : { outcome: "awaiting" };
1766
- }
1767
- if (piece.id === "field:system-prompt" || piece.id === "field:post-history") return reported ? {
1768
- outcome: "guidance",
1769
- because: "instructions to the narrator"
1770
- } : { outcome: "awaiting" };
1771
- if (piece.enabled !== void 0 && choices.disabledEntries.includes(piece.id)) return {
1772
- outcome: "omitted",
1773
- because: "left off by the person"
1440
+ function parseCalendarFile(text) {
1441
+ const issues = [];
1442
+ const reader = Reader.fromJson(text, issues);
1443
+ if (reader === void 0) return {
1444
+ ok: false,
1445
+ issues
1774
1446
  };
1775
- if (piece.enabled === false && !(card.book?.entries.find((entry) => entry.id === piece.id)?.enabled ?? true) && !piece.used) return {
1776
- outcome: "omitted",
1777
- because: "switched off in the card"
1447
+ const hemisphere = reader.oneOf("hemisphere", ["north", "south"], "north");
1448
+ const seen = /* @__PURE__ */ new Set();
1449
+ const holidays = reader.objects("holidays").flatMap((entry) => {
1450
+ const id = entry.string("id", { required: true });
1451
+ const name = entry.string("name", { required: true });
1452
+ const on = entry.strings("on");
1453
+ if (id !== void 0 && !HOLIDAY_ID.test(id)) entry.fail("id", "is made of letters, digits, \"-\" and \"_\" (at most 60)");
1454
+ if (id !== void 0 && seen.has(id)) entry.fail("id", `"${id}" is used by another holiday`);
1455
+ if (id !== void 0) seen.add(id);
1456
+ if (on.length === 0) entry.fail("on", `names no day: write days such as "12-25", "09-21..09-22", "nth:mon:1" or a month (${MONTH_NAMES.join(", ")}); seasons are ${SEASONS.join(", ")}`);
1457
+ for (const problem of dayTokenProblems(on, "on")) entry.fail("on", problem.replace(/^on: /, ""));
1458
+ return id === void 0 || name === void 0 ? [] : [{
1459
+ id,
1460
+ name,
1461
+ on
1462
+ }];
1463
+ });
1464
+ if (holidays.length > 60) reader.fail("holidays", `a world has at most 60 holidays`);
1465
+ return issues.length > 0 ? {
1466
+ ok: false,
1467
+ issues
1468
+ } : {
1469
+ ok: true,
1470
+ value: {
1471
+ hemisphere,
1472
+ holidays
1473
+ }
1778
1474
  };
1779
- if (source.records.classified === void 0) return { outcome: "awaiting" };
1780
- const roles = rolesOf$1(source, piece.id);
1781
- if (roles.length === 0) return {
1782
- outcome: "awaiting",
1783
- because: "the import did not classify it"
1475
+ }
1476
+ /** The calendar of a world: an optional `<world>/calendar.json`; a world without one has none. */
1477
+ async function loadCalendar(worldDir) {
1478
+ const result = {
1479
+ calendar: {
1480
+ hemisphere: "north",
1481
+ holidays: []
1482
+ },
1483
+ problems: []
1784
1484
  };
1785
- if (roles.every((role) => ROLE_TABLE[role].leftOut)) {
1786
- if (mechanics) return {
1787
- outcome: "converted",
1788
- because: "its rules became tracked values, rules or triggers"
1789
- };
1790
- return roles.includes("instruction") ? {
1791
- outcome: "guidance",
1792
- because: "how to run a story, not facts of this one"
1793
- } : {
1794
- outcome: "omitted",
1795
- because: roles.includes("template") ? "a template or format of the source tool" : "nothing to do with the story"
1796
- };
1485
+ const file = join(worldDir, CALENDAR_FILE_NAME);
1486
+ try {
1487
+ result.calendar = await readDocument$1(file, parseCalendarFile, result.problems) ?? result.calendar;
1488
+ } catch (error) {
1489
+ if (error.code !== "ENOENT") result.problems.push({
1490
+ path: file,
1491
+ message: errorMessage(error)
1492
+ });
1797
1493
  }
1798
- if (made.length > 0 || mechanics) return {
1799
- outcome: "converted",
1800
- ...made.length === 0 ? { because: "its rules became tracked values, rules or triggers" } : {}
1801
- };
1802
- return {
1803
- outcome: "read",
1804
- because: "no character, place, thing or rule is made from it: its words survive only as background"
1494
+ return result;
1495
+ }
1496
+ // src/host/dice/load.ts
1497
+ const DICE_FILE_NAME = "dice.json";
1498
+ function readBand(band) {
1499
+ const label = band.string("label", { required: true });
1500
+ const result = band.oneOf("result", DICE_RESULTS, "failed");
1501
+ const min = band.number("min");
1502
+ const max = band.number("max");
1503
+ const critical = band.raw("critical");
1504
+ if (critical !== void 0 && critical !== null && typeof critical !== "boolean") band.fail("critical", "must be true or false");
1505
+ if (band.raw("result") === void 0) band.fail("result", `is required: one of ${DICE_RESULTS.join(", ")}`);
1506
+ return label === void 0 ? void 0 : {
1507
+ label,
1508
+ result,
1509
+ ...min === void 0 ? {} : { min },
1510
+ ...max === void 0 ? {} : { max },
1511
+ ...critical === true ? { critical: true } : {}
1805
1512
  };
1806
1513
  }
1807
- /** What became of every piece of the card, from the import's records; `made` is `entitiesByPiece` of the same source. */
1808
- function pieceOutcomes(source, made, options = {}) {
1809
- const derived = options.derived ?? source.records.report?.derived ?? [];
1810
- return source.pieces.map((piece) => {
1811
- const from = derived.filter((entry) => entry.pieces.includes(piece.id));
1812
- const labels = from.map((entry) => `${entry.kind}: ${entry.name}`);
1813
- return {
1814
- piece: piece.id,
1815
- label: piece.label,
1816
- ...outcomeOf(source, piece, made.get(piece.id) ?? [], from.some((entry) => MECHANICS.includes(entry.kind)), options.finished === true),
1817
- madeInto: [...made.get(piece.id) ?? [], ...labels]
1514
+ /**
1515
+ * Read `dice.json`: the checks a world settles uncertain attempts with (docs/world-format.md). The dice and how their result is read are the world's:
1516
+ * the game master rolls a check and is told the band the roll fell in, never a number to interpret.
1517
+ */
1518
+ function parseDiceFile(text) {
1519
+ const issues = [];
1520
+ const reader = Reader.fromJson(text, issues);
1521
+ if (reader === void 0) return {
1522
+ ok: false,
1523
+ issues
1524
+ };
1525
+ const checks = reader.objects("checks").flatMap((entry) => {
1526
+ const key = entry.string("key", { required: true });
1527
+ const name = entry.string("name", { required: true });
1528
+ const use = entry.string("use", { required: true });
1529
+ const dice = entry.string("dice", { required: true });
1530
+ const reading = entry.oneOf("reading", DICE_READINGS, "total");
1531
+ const compare = entry.oneOf("compare", DICE_COMPARISONS, "absolute");
1532
+ const hit = entry.number("hit", { min: 1 });
1533
+ const modifier = entry.string("modifier");
1534
+ const bands = entry.objects("bands").flatMap((band) => {
1535
+ const read = readBand(band);
1536
+ return read === void 0 ? [] : [read];
1537
+ });
1538
+ if (key === void 0 || name === void 0 || use === void 0 || dice === void 0) return [];
1539
+ const definition = {
1540
+ key,
1541
+ name,
1542
+ use,
1543
+ dice,
1544
+ reading,
1545
+ compare,
1546
+ bands,
1547
+ ...hit === void 0 ? {} : { hit },
1548
+ ...modifier === void 0 || modifier === "" ? {} : { modifier }
1818
1549
  };
1550
+ for (const problem of checkProblems(definition)) entry.fail("", problem);
1551
+ return [definition];
1819
1552
  });
1553
+ const seen = /* @__PURE__ */ new Set();
1554
+ for (const check of checks) {
1555
+ if (seen.has(check.key)) reader.fail("checks", `the key "${check.key}" is used by more than one check`);
1556
+ seen.add(check.key);
1557
+ }
1558
+ if (checks.length > 40) reader.fail("checks", `a world has at most 40 checks`);
1559
+ return issues.length > 0 ? {
1560
+ ok: false,
1561
+ issues
1562
+ } : {
1563
+ ok: true,
1564
+ value: checks
1565
+ };
1820
1566
  }
1821
- const outcomeCounts = (outcomes) => Object.fromEntries(OUTCOMES.map((outcome) => [outcome, outcomes.filter((entry) => entry.outcome === outcome).length]));
1822
- // src/host/import/card-tools.ts
1823
- /** The most of a piece one `card_read` returns; a long lorebook entry is read in turns. */
1824
- const READ_CHARS = 6e3;
1825
- const SNIPPET_CHARS = 240;
1826
- const DEFAULT_HITS = 8;
1827
- const MAX_HITS = 20;
1828
- const baseId = (id) => id.replace(/#\d+$/, "");
1829
- /** The folder inside `.import` where a newer version of the card waits to be applied to the world. */
1830
- const UPDATE_FOLDER = "update";
1831
- /** Everything the card holds, in the order the card has it. */
1832
- function cardPieces(card, choices) {
1833
- const read = new Set(itemise(card, choices).map((item) => baseId(item.id)));
1834
- const field = (id, label, text) => text.trim() === "" ? [] : [{
1835
- id,
1836
- label,
1837
- title: "",
1838
- keys: [],
1839
- text,
1840
- used: read.has(id)
1841
- }];
1842
- return [
1843
- ...field("field:description", "description", card.description),
1844
- ...field("field:personality", "personality", card.personality),
1845
- ...field("field:scenario", "scenario", card.scenario),
1846
- ...field("field:example", "example messages", card.messageExample),
1847
- ...field("field:first-message", "first message", card.firstMessage),
1848
- ...card.alternateGreetings.flatMap((text, index) => field(`field:greeting-${index + 1}`, `alternate greeting ${index + 1}`, text)),
1849
- ...field("field:creator-notes", "creator's notes", card.creatorNotes),
1850
- ...field("field:system-prompt", "system prompt", card.systemPrompt),
1851
- ...field("field:post-history", "post-history instructions", card.postHistoryInstructions),
1852
- ...(card.book?.entries ?? []).filter((entry) => entry.content.trim() !== "").map((entry) => ({
1853
- id: entry.id,
1854
- label: entry.title === "" ? entry.id : `entry “${entry.title}”`,
1855
- title: entry.title,
1856
- keys: entry.keys,
1857
- text: entry.content,
1858
- used: read.has(entry.id),
1859
- enabled: entry.enabled
1860
- }))
1861
- ];
1862
- }
1863
- async function optional(file) {
1567
+ /** The checks of a world: an optional `<world>/dice.json`; a world without one has none, and its game master rolls plain dice only. */
1568
+ async function loadDice(worldDir) {
1569
+ const result = {
1570
+ checks: [],
1571
+ problems: []
1572
+ };
1573
+ const file = join(worldDir, DICE_FILE_NAME);
1864
1574
  try {
1865
- return JSON.parse(await readFile(file, "utf8"));
1575
+ result.checks = await readDocument$1(file, parseDiceFile, result.problems) ?? [];
1866
1576
  } catch (error) {
1867
- if (error.code === "ENOENT") return void 0;
1868
- throw error;
1577
+ if (error.code !== "ENOENT") result.problems.push({
1578
+ path: file,
1579
+ message: errorMessage(error)
1580
+ });
1869
1581
  }
1582
+ return result;
1870
1583
  }
1871
- /** 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. */
1872
- async function readSource(directory, withRecords, version = "current") {
1873
- const folder = join(directory, IMPORT_FOLDER);
1874
- let read;
1584
+ // src/host/factions/load.ts
1585
+ const FACTIONS_DIR = "factions";
1586
+ async function loadFactions(worldDir) {
1587
+ const dir = join(worldDir, FACTIONS_DIR);
1588
+ const result = {
1589
+ factions: [],
1590
+ problems: []
1591
+ };
1592
+ let folders;
1875
1593
  try {
1876
- read = await readImportFolder(version === "new" ? join(folder, UPDATE_FOLDER) : folder);
1594
+ folders = await subfolders(dir);
1877
1595
  } catch (error) {
1878
- 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");
1879
- throw error;
1596
+ if (error.code !== "ENOENT") result.problems.push({
1597
+ path: dir,
1598
+ message: errorMessage(error)
1599
+ });
1600
+ return result;
1880
1601
  }
1881
- const records = withRecords && version === "current" ? {
1882
- classified: await optional(join(folder, "classification.json")),
1883
- roster: await optional(join(folder, "roster.json")),
1884
- report: await optional(join(folder, "report.json"))
1885
- } : {};
1886
- return {
1887
- card: read.card,
1888
- choices: read.choices,
1889
- pieces: cardPieces(read.card, read.choices),
1890
- records
1891
- };
1892
- }
1893
- const rolesOf = (classified, id) => {
1894
- if (classified === void 0) return [];
1895
- return [...new Set(Object.entries(classified).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
1896
- };
1897
- function snippet$1(text, at, length) {
1898
- const start = Math.max(0, at - Math.floor((SNIPPET_CHARS - length) / 2));
1899
- const end = Math.min(text.length, start + SNIPPET_CHARS);
1900
- return `${start > 0 ? "…" : ""}${text.slice(start, end).replace(/\s+/g, " ")}${end < text.length ? "…" : ""}`;
1901
- }
1902
- function searchPieces(pieces, query, limit) {
1903
- const phrase = query.trim().toLowerCase();
1904
- if (phrase === "") return [];
1905
- const words = [...new Set(phrase.split(/[\s,;,、]+/).filter((word) => word.length >= (/^[\x00-\x7f]+$/.test(word) ? 3 : 2)))];
1906
- const count = (text, needle) => {
1907
- let n = 0;
1908
- let first = -1;
1909
- for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
1910
- n += 1;
1911
- if (first < 0) first = at;
1602
+ const owners = /* @__PURE__ */ new Map();
1603
+ for (const folder of folders) {
1604
+ const file = join(dir, folder, FACTION_FILE_NAME);
1605
+ try {
1606
+ const faction = await readDocument$1(file, (text) => parseFactionFile(text, folder), result.problems);
1607
+ if (faction === void 0) continue;
1608
+ const owner = owners.get(faction.id);
1609
+ if (owner !== void 0) {
1610
+ result.problems.push({
1611
+ path: file,
1612
+ message: `id "${faction.id}" is already used by ${owner}`
1613
+ });
1614
+ continue;
1615
+ }
1616
+ owners.set(faction.id, folder);
1617
+ result.factions.push(faction);
1618
+ } catch (error) {
1619
+ if (error.code !== "ENOENT") result.problems.push({
1620
+ path: file,
1621
+ message: errorMessage(error)
1622
+ });
1912
1623
  }
1913
- return {
1914
- n,
1915
- first
1916
- };
1917
- };
1918
- const look = (text) => {
1919
- const lowered = text.toLowerCase();
1920
- const whole = count(lowered, phrase);
1921
- if (whole.n > 0) return {
1922
- matches: whole.n,
1923
- score: whole.n * 4 + 100,
1924
- at: whole.first,
1925
- length: phrase.length
1926
- };
1927
- const found = words.map((word) => ({
1928
- word,
1929
- ...count(lowered, word)
1930
- })).filter((entry) => entry.n > 0);
1931
- if (found.length === 0) return void 0;
1932
- const best = found.reduce((a, b) => a.first <= b.first ? a : b, found[0]);
1933
- return {
1934
- matches: found.reduce((sum, entry) => sum + entry.n, 0),
1935
- score: found.length * 10 + found.reduce((sum, entry) => sum + entry.n, 0),
1936
- at: best.first,
1937
- length: best.word.length
1938
- };
1939
- };
1940
- return pieces.flatMap((piece) => {
1941
- const inText = look(piece.text);
1942
- if (inText !== void 0) return [{
1943
- piece,
1944
- in: "text",
1945
- matches: inText.matches,
1946
- score: inText.score,
1947
- snippet: snippet$1(piece.text, inText.at, inText.length)
1948
- }];
1949
- const head = [piece.title, ...piece.keys].filter((part) => part !== "").join(" · ");
1950
- const inHead = look(head);
1951
- return inHead === void 0 ? [] : [{
1952
- piece,
1953
- in: "title or keys",
1954
- matches: inHead.matches,
1955
- score: inHead.score - 50,
1956
- snippet: `${piece.title === "" ? "" : `title: ${piece.title}`}${piece.keys.length === 0 ? "" : `${piece.title === "" ? "" : "; "}keys: ${piece.keys.join(", ")}`}`
1957
- }];
1958
- }).sort((a, b) => b.score - a.score).slice(0, limit).map(({ piece, matches, in: where, snippet: text }) => ({
1959
- piece,
1960
- matches,
1961
- in: where,
1962
- snippet: text
1963
- }));
1624
+ }
1625
+ if (result.factions.length > 100) result.problems.push({
1626
+ path: dir,
1627
+ message: `a world has at most 100 factions`
1628
+ });
1629
+ return result;
1964
1630
  }
1965
- const versionParameter = {
1966
- type: "string",
1967
- enum: ["current", "new"],
1968
- 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."
1969
- };
1970
- const output$1 = {
1971
- schema: { type: "json" },
1972
- render: (_args, value) => [{
1973
- type: "text",
1974
- text: JSON.stringify(value, null, 1)
1975
- }]
1976
- };
1977
- const json$1 = (value) => JSON.parse(JSON.stringify(value));
1978
- const idOf = (exec) => {
1979
- const chat = exec.agent?.session.id;
1980
- const world = chat === void 0 ? void 0 : authoredWorldOf(chat);
1981
- if (world === void 0) throw new Error("this tool is available only in a world authoring chat");
1982
- return world;
1983
- };
1631
+ // src/host/items/load.ts
1632
+ const ITEMS_DIR = "items";
1633
+ /** At most this many items in one world. */
1634
+ const MAX_ITEMS = 2e3;
1984
1635
  /**
1985
- * 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.
1986
- * `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.
1636
+ * Read the things of one world: every subfolder of `<world>/items/` that holds an `item.json`, and an
1637
+ * optional `<world>/items/slots.json`. A world with no such folder has none. Ids must be unique; what
1638
+ * a thing is worn in must be a slot, and where it starts, who owns it, what opens it and what it is
1639
+ * inside must exist in the world, with no thing inside itself.
1987
1640
  */
1988
- function cardTools(worlds, options = {}) {
1989
- const withRecords = options.records !== false;
1990
- const source = async (exec, version = "current") => {
1991
- const id = idOf(exec);
1992
- const record = await worlds.find(id);
1993
- if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
1994
- return await readSource(record.directory, withRecords, version);
1995
- };
1996
- const versionOf = (value) => {
1997
- if (value === void 0 || value === "current") return "current";
1998
- if (value === "new") return "new";
1999
- throw new Error("version must be current or new");
2000
- };
2001
- const find = (pieces, id) => {
2002
- const found = pieces.find((piece) => piece.id === id);
2003
- if (found === void 0) throw new Error(`the card has no piece "${id}": use an id from card_overview or card_search`);
2004
- return found;
2005
- };
2006
- return [
2007
- defineTool({
2008
- name: "card_overview",
2009
- 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.",
2010
- parameters: {},
2011
- output: output$1,
2012
- isConcurrencySafe: () => true,
2013
- async execute(_args, exec) {
2014
- const { card, choices, pieces, records } = await source(exec);
2015
- const madeFrom = entitiesByPiece({
2016
- card,
2017
- choices,
2018
- pieces,
2019
- records
2020
- });
2021
- const made = (id) => madeFrom.get(id) ?? [];
2022
- const outcomes = withRecords ? pieceOutcomes({
2023
- card,
2024
- choices,
2025
- pieces,
2026
- records
2027
- }, madeFrom) : [];
2028
- return json$1({
2029
- card: {
2030
- name: card.name,
2031
- creator: card.creator,
2032
- version: card.characterVersion,
2033
- tags: card.tags,
2034
- format: card.sourceSpec,
2035
- ignoredScripts: card.ignored.scripts
2036
- },
2037
- ...withRecords ? { outcomes: outcomeCounts(outcomes) } : {},
2038
- pieces: pieces.map((piece) => ({
2039
- id: piece.id,
2040
- label: piece.label,
2041
- characters: piece.text.length,
2042
- readByTheImport: piece.used,
2043
- ...withRecords ? {
2044
- outcome: outcomes.find((entry) => entry.piece === piece.id)?.outcome,
2045
- because: outcomes.find((entry) => entry.piece === piece.id)?.because
2046
- } : {},
2047
- ...piece.enabled === void 0 ? {} : { switchedOnInCard: piece.enabled },
2048
- ...withRecords ? {
2049
- takenToBe: rolesOf(records.classified, piece.id),
2050
- madeInto: made(piece.id)
2051
- } : {}
2052
- })),
2053
- ...records.roster === void 0 ? {} : { imported: records.roster.map((entity) => ({
2054
- name: entity.name,
2055
- kind: entity.kind,
2056
- aliases: entity.aliases,
2057
- playedByThePlayer: entity.player
2058
- })) },
2059
- ...records.report === void 0 ? {} : {
2060
- importNotes: records.report.notes,
2061
- leftOut: records.report.leftOut
2062
- },
2063
- 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."
1641
+ async function loadItems(worldDir, context) {
1642
+ const dir = join(worldDir, ITEMS_DIR);
1643
+ const result = {
1644
+ items: [],
1645
+ slots: DEFAULT_SLOTS.map((slot) => ({ ...slot })),
1646
+ problems: []
1647
+ };
1648
+ let folders;
1649
+ try {
1650
+ folders = await subfolders(dir);
1651
+ } catch (error) {
1652
+ if (error.code !== "ENOENT") result.problems.push({
1653
+ path: dir,
1654
+ message: errorMessage(error)
1655
+ });
1656
+ return result;
1657
+ }
1658
+ try {
1659
+ const own = await readDocument$1(join(dir, SLOTS_FILE_NAME), parseSlotsFile, result.problems);
1660
+ for (const slot of own ?? []) {
1661
+ const at = result.slots.findIndex((existing) => existing.id === slot.id);
1662
+ if (at < 0) result.slots.push(slot);
1663
+ else result.slots[at] = slot;
1664
+ }
1665
+ } catch (error) {
1666
+ if (error.code !== "ENOENT") result.problems.push({
1667
+ path: join(dir, SLOTS_FILE_NAME),
1668
+ message: errorMessage(error)
1669
+ });
1670
+ }
1671
+ const folderOf = /* @__PURE__ */ new Map();
1672
+ for (const folder of folders) {
1673
+ const file = join(dir, folder, ITEM_FILE_NAME);
1674
+ try {
1675
+ const item = await readDocument$1(file, (text) => parseItemFile(text, folder), result.problems);
1676
+ if (item === void 0) continue;
1677
+ const owner = folderOf.get(item.id);
1678
+ if (owner !== void 0) {
1679
+ result.problems.push({
1680
+ path: file,
1681
+ message: `id "${item.id}" is already used by ${owner}`
2064
1682
  });
1683
+ continue;
2065
1684
  }
2066
- }),
2067
- defineTool({
2068
- name: "card_search",
2069
- 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.",
2070
- parameters: {
2071
- query: {
2072
- type: "string",
2073
- required: true,
2074
- description: "A name or phrase to look for, in the card's own language."
2075
- },
2076
- version: versionParameter,
2077
- limit: {
2078
- type: "number",
2079
- description: `How many pieces to return, at most ${MAX_HITS} (default ${DEFAULT_HITS}).`
1685
+ folderOf.set(item.id, folder);
1686
+ result.items.push(item);
1687
+ } catch (error) {
1688
+ if (error.code !== "ENOENT") result.problems.push({
1689
+ path: file,
1690
+ message: errorMessage(error)
1691
+ });
1692
+ }
1693
+ }
1694
+ if (result.items.length > 2e3) result.problems.push({
1695
+ path: dir,
1696
+ message: `a world has at most ${MAX_ITEMS} items`
1697
+ });
1698
+ const byId = new Map(result.items.map((item) => [item.id, item]));
1699
+ const slotIds = new Set(result.slots.map((slot) => slot.id));
1700
+ const places = new Map(context.locations.map((location) => [location.id, location]));
1701
+ const characters = new Set(context.characters);
1702
+ const fileOf = (id) => join(dir, folderOf.get(id) ?? id, ITEM_FILE_NAME);
1703
+ for (const item of result.items) {
1704
+ const problem = (message) => {
1705
+ result.problems.push({
1706
+ path: fileOf(item.id),
1707
+ message
1708
+ });
1709
+ };
1710
+ if (item.wearable !== void 0 && !slotIds.has(item.wearable)) problem(`wearable: "${item.wearable}" is not a slot (the slots are: ${[...slotIds].join(", ")}; add one in ${SLOTS_FILE_NAME})`);
1711
+ if (item.owner !== void 0 && !characters.has(item.owner)) problem(`owner: "${item.owner}" is not a character of this world`);
1712
+ for (const key of item.container?.openedBy ?? []) if (!byId.has(key)) problem(`container.opened_by: "${key}" is not an item of this world`);
1713
+ const { start } = item;
1714
+ if (start.kind === "location") {
1715
+ const place = places.get(start.location);
1716
+ if (place === void 0) problem(`location: "${start.location}" is not a place of this world`);
1717
+ else if (start.feature !== void 0 && !place.features.some((feature) => feature.key === start.feature)) problem(`feature: ${place.name} has no feature "${start.feature}"`);
1718
+ } else if (start.kind === "held" || start.kind === "worn") {
1719
+ if (!characters.has(start.character)) problem(`${start.kind === "held" ? "held_by" : "worn_by"}: "${start.character}" is not a character of this world`);
1720
+ } else if (start.kind === "inside") {
1721
+ const box = byId.get(start.item);
1722
+ if (box === void 0) problem(`inside: "${start.item}" is not an item of this world`);
1723
+ else if (box.container === void 0) problem(`inside: ${box.name} is not a container`);
1724
+ const seen = /* @__PURE__ */ new Set([item.id]);
1725
+ for (let up = box; up !== void 0; up = up.start.kind === "inside" ? byId.get(up.start.item) : void 0) {
1726
+ if (seen.has(up.id)) {
1727
+ problem("inside: the items are inside each other in a circle");
1728
+ break;
2080
1729
  }
2081
- },
2082
- output: output$1,
2083
- isConcurrencySafe: () => true,
2084
- async execute(args, exec) {
2085
- const { pieces } = await source(exec, versionOf(args.version));
2086
- const limit = Math.min(MAX_HITS, Math.max(1, Math.floor(typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : DEFAULT_HITS)));
2087
- const hits = searchPieces(pieces, args.query, limit);
2088
- return json$1({
2089
- query: args.query,
2090
- found: hits.length,
2091
- hits: hits.map(({ piece, matches, in: where, snippet: text }) => ({
2092
- piece: piece.id,
2093
- label: piece.label,
2094
- matches,
2095
- foundIn: where,
2096
- snippet: text
2097
- }))
2098
- });
1730
+ seen.add(up.id);
2099
1731
  }
2100
- }),
2101
- defineTool({
2102
- name: "card_read",
2103
- 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.`,
2104
- parameters: {
2105
- piece: {
2106
- type: "string",
2107
- required: true,
2108
- description: "A piece id from card_overview, card_search or card_diff, such as field:description or entry:3."
2109
- },
2110
- version: versionParameter,
2111
- offset: {
2112
- type: "number",
2113
- description: "Where to start reading, in characters (default 0)."
2114
- }
2115
- },
2116
- output: output$1,
2117
- isConcurrencySafe: () => true,
2118
- async execute(args, exec) {
2119
- const { pieces } = await source(exec, versionOf(args.version));
2120
- const piece = find(pieces, args.piece);
2121
- const from = Math.min(piece.text.length, Math.max(0, Math.floor(typeof args.offset === "number" && Number.isFinite(args.offset) ? args.offset : 0)));
2122
- const to = Math.min(piece.text.length, from + READ_CHARS);
2123
- return json$1({
2124
- piece: piece.id,
2125
- label: piece.label,
2126
- ...piece.keys.length === 0 ? {} : { keys: piece.keys },
2127
- from,
2128
- to,
2129
- of: piece.text.length,
2130
- ...to < piece.text.length ? { next: to } : {},
2131
- text: piece.text.slice(from, to)
1732
+ }
1733
+ }
1734
+ for (const place of context.locations) place.exits.forEach((exit, index) => {
1735
+ for (const key of exit.openedBy ?? []) if (!byId.has(key)) result.problems.push({
1736
+ path: join(worldDir, "locations", place.id, "location.json"),
1737
+ message: `exits[${index}].opened_by: "${key}" is not an item of this world`
1738
+ });
1739
+ });
1740
+ return result;
1741
+ }
1742
+ /** The items in an order where each comes after the container it starts in. */
1743
+ function containersFirst(items) {
1744
+ const ordered = [];
1745
+ const placed = /* @__PURE__ */ new Set();
1746
+ const byId = new Map(items.map((item) => [item.id, item]));
1747
+ const place = (item) => {
1748
+ if (placed.has(item.id)) return;
1749
+ placed.add(item.id);
1750
+ const box = item.start.kind === "inside" ? byId.get(item.start.item) : void 0;
1751
+ if (box !== void 0) place(box);
1752
+ ordered.push(item);
1753
+ };
1754
+ for (const item of items) place(item);
1755
+ return ordered;
1756
+ }
1757
+ // src/host/locations/load.ts
1758
+ const LOCATIONS_DIR = "locations";
1759
+ /**
1760
+ * Read the places of one world: every subfolder of `<world>/locations/` that holds a
1761
+ * `location.json`. A world with no such folder has no places, which is fine. Ids must be unique;
1762
+ * every parent and every exit must lead to a place of the world, and the places must not contain
1763
+ * each other in a circle. Every problem is reported with the file it is in.
1764
+ */
1765
+ async function loadLocations(worldDir) {
1766
+ const dir = join(worldDir, LOCATIONS_DIR);
1767
+ const result = {
1768
+ locations: [],
1769
+ problems: []
1770
+ };
1771
+ let folders;
1772
+ try {
1773
+ folders = await subfolders(dir);
1774
+ } catch (error) {
1775
+ if (error.code !== "ENOENT") result.problems.push({
1776
+ path: dir,
1777
+ message: errorMessage(error)
1778
+ });
1779
+ return result;
1780
+ }
1781
+ const files = /* @__PURE__ */ new Map();
1782
+ for (const folder of folders) {
1783
+ const file = join(dir, folder, LOCATION_FILE_NAME);
1784
+ try {
1785
+ const location = await readDocument$1(file, (text) => parseLocationFile(text, folder), result.problems);
1786
+ if (location === void 0) continue;
1787
+ const owner = files.get(location.id);
1788
+ if (owner !== void 0) {
1789
+ result.problems.push({
1790
+ path: file,
1791
+ message: `id "${location.id}" is already used by ${owner}`
2132
1792
  });
1793
+ continue;
2133
1794
  }
2134
- }),
2135
- defineTool({
2136
- name: "card_origin",
2137
- 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.",
2138
- parameters: { name: {
2139
- type: "string",
2140
- required: true,
2141
- description: "The name or an alias, as the world or the card has it."
2142
- } },
2143
- output: output$1,
2144
- isConcurrencySafe: () => true,
2145
- async execute(args, exec) {
2146
- const { card, choices, pieces, records } = await source(exec);
2147
- const entity = records.roster === void 0 ? void 0 : findEntity(records.roster, args.name);
2148
- if (entity === void 0 || records.classified === void 0) return json$1({
2149
- name: args.name,
2150
- madeByTheImport: false,
2151
- mentions: searchPieces(pieces, args.name, DEFAULT_HITS).map(({ piece, in: where, snippet: text }) => ({
2152
- piece: piece.id,
2153
- label: piece.label,
2154
- foundIn: where,
2155
- snippet: text
2156
- }))
2157
- });
2158
- return json$1({
2159
- name: entity.name,
2160
- kind: entity.kind,
2161
- aliases: entity.aliases,
2162
- madeByTheImport: true,
2163
- usedPieces: originOf(card, choices, pieces, records, entity.name).map((entry) => ({
2164
- piece: entry.piece,
2165
- label: entry.label,
2166
- how: entry.how,
2167
- takenToBe: rolesOf(records.classified, entry.piece)
2168
- }))
1795
+ files.set(location.id, folder);
1796
+ result.locations.push(location);
1797
+ } catch (error) {
1798
+ if (error.code !== "ENOENT") result.problems.push({
1799
+ path: file,
1800
+ message: errorMessage(error)
1801
+ });
1802
+ }
1803
+ }
1804
+ if (result.locations.length > 500) result.problems.push({
1805
+ path: dir,
1806
+ message: `a world has at most 500 places`
1807
+ });
1808
+ const byId = new Map(result.locations.map((location) => [location.id, location]));
1809
+ const fileOf = (id) => join(dir, files.get(id) ?? id, LOCATION_FILE_NAME);
1810
+ for (const location of result.locations) {
1811
+ if (location.parent !== void 0 && !byId.has(location.parent)) result.problems.push({
1812
+ path: fileOf(location.id),
1813
+ message: `parent: "${location.parent}" is not a place of this world`
1814
+ });
1815
+ if (location.parent === location.id) result.problems.push({
1816
+ path: fileOf(location.id),
1817
+ message: "parent: a place cannot be in itself"
1818
+ });
1819
+ location.exits.forEach((exit, index) => {
1820
+ if (!byId.has(exit.to)) result.problems.push({
1821
+ path: fileOf(location.id),
1822
+ message: `exits[${index}].to: "${exit.to}" is not a place of this world`
1823
+ });
1824
+ if (exit.to === location.id) result.problems.push({
1825
+ path: fileOf(location.id),
1826
+ message: `exits[${index}].to: an exit must lead to another place`
1827
+ });
1828
+ });
1829
+ const seen = /* @__PURE__ */ new Set();
1830
+ for (let up = location.parent === location.id ? void 0 : location.parent; up !== void 0 && byId.has(up); up = byId.get(up)?.parent) {
1831
+ if (up === location.id || seen.has(up)) {
1832
+ result.problems.push({
1833
+ path: fileOf(location.id),
1834
+ message: "parent: the places contain each other in a circle"
2169
1835
  });
1836
+ break;
2170
1837
  }
2171
- })
2172
- ];
1838
+ seen.add(up);
1839
+ }
1840
+ }
1841
+ return result;
2173
1842
  }
2174
- /** For each piece of the card, the names of the characters, places and things the import made from it. */
2175
- function entitiesByPiece(source) {
2176
- const made = /* @__PURE__ */ new Map();
2177
- 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]);
2178
- return made;
1843
+ /** The places in an order where each comes after the one it is in. */
1844
+ function parentsFirst(locations) {
1845
+ const ordered = [];
1846
+ const placed = /* @__PURE__ */ new Set();
1847
+ const byId = new Map(locations.map((location) => [location.id, location]));
1848
+ const place = (location) => {
1849
+ if (placed.has(location.id)) return;
1850
+ placed.add(location.id);
1851
+ const parent = location.parent === void 0 ? void 0 : byId.get(location.parent);
1852
+ if (parent !== void 0) place(parent);
1853
+ ordered.push(location);
1854
+ };
1855
+ for (const location of locations) place(location);
1856
+ return ordered;
1857
+ }
1858
+ // src/host/sessions/populate.ts
1859
+ /** What is wrong with how the characters stand towards each other, found before anything is created. */
1860
+ function relationshipProblems(characters) {
1861
+ const ids = new Set(characters.map((character) => character.id));
1862
+ return characters.flatMap((character) => (character.relationships ?? []).flatMap((relation) => {
1863
+ if (relation.to === character.id) return [`${character.id}: relationships: a character has no relationship with itself`];
1864
+ return ids.has(relation.to) ? [] : [`${character.id}: relationships: "${relation.to}" is not a character of this world`];
1865
+ }));
1866
+ }
1867
+ function factionProblems(factions, characters) {
1868
+ const factionIds = new Set(factions.map((faction) => faction.id));
1869
+ const characterIds = new Set(characters.map((character) => character.id));
1870
+ return factions.flatMap((faction) => [...faction.members.flatMap((member) => characterIds.has(member.character) ? [] : [`${faction.id}: members: "${member.character}" is not a character of this world`]), ...faction.relationships.flatMap((relation) => {
1871
+ if (relation.to.kind === "faction" && relation.to.id === faction.id) return [`${faction.id}: relationships: a faction has no relationship with itself`];
1872
+ return (relation.to.kind === "character" ? characterIds : factionIds).has(relation.to.id) ? [] : [`${faction.id}: relationships: "${relation.to.id}" is not a ${relation.to.kind} of this world`];
1873
+ })]);
1874
+ }
1875
+ /** What is wrong with the places, things and directed ways characters are authored to know. */
1876
+ function knowledgeProblems(characters, locations, items, lore = []) {
1877
+ const places = new Map(locations.map((location) => [location.id, location]));
1878
+ const things = new Set(items.map((item) => item.id));
1879
+ const loreIds = new Set(lore.map((entry) => entry.id));
1880
+ const wayExists = (from, to) => places.get(from)?.exits.some((exit) => exit.to === to) === true || places.get(to)?.exits.some((exit) => exit.to === from && !exit.oneWay) === true;
1881
+ return characters.flatMap((character) => {
1882
+ const prefix = `${character.id}: knowledge`;
1883
+ const knowledge = character.knowledge;
1884
+ if (knowledge === void 0) return [];
1885
+ return [
1886
+ ...knowledge.locations.flatMap((key) => places.has(key) ? [] : [`${prefix}.locations: "${key}" is not a place of this world`]),
1887
+ ...knowledge.items.flatMap((key) => things.has(key) ? [] : [`${prefix}.items: "${key}" is not an item of this world`]),
1888
+ ...knowledge.exits.flatMap(({ from, to }) => wayExists(from, to) ? [] : [`${prefix}.exits: there is no exit from "${from}" to "${to}"`]),
1889
+ ...(knowledge.lore ?? []).flatMap((key) => loreIds.has(key) ? [] : [`${prefix}.lore: "${key}" is not lore of this world`])
1890
+ ];
1891
+ });
1892
+ }
1893
+ /** Whether a world's characters include the one a lore entry names by id, name or alias. */
1894
+ function knowsCharacter(characters, reference) {
1895
+ const key = reference.normalize("NFKC").toLowerCase();
1896
+ return characters.some((character) => character.id === reference || [character.name, ...character.aliases].some((name) => name.normalize("NFKC").toLowerCase() === key));
1897
+ }
1898
+ function loreProblems(lore, world) {
1899
+ const ids = {
1900
+ character: new Set(world.characters.map((x) => x.id)),
1901
+ faction: new Set(world.factions.map((x) => x.id)),
1902
+ location: new Set(world.locations.map((x) => x.id)),
1903
+ item: new Set(world.items.map((x) => x.id)),
1904
+ lore: new Set(lore.map((x) => x.id))
1905
+ };
1906
+ return lore.flatMap((entry) => [
1907
+ ...entry.subjects.flatMap((subject) => ids[subject.kind].has(subject.id) ? [] : [`${entry.id}: subjects: "${subject.id}" is not a ${subject.kind} of this world`]),
1908
+ ...entry.knownBy.flatMap((reference) => knowsCharacter(world.characters, reference) ? [] : [`${entry.id}: known_by: "${reference}" is not a character of this world`]),
1909
+ ...entry.related.flatMap((id) => id === entry.id ? [`${entry.id}: related: lore cannot relate to itself`] : ids.lore.has(id) ? [] : [`${entry.id}: related: "${id}" is not lore of this world`])
1910
+ ]);
1911
+ }
1912
+ /** `turn` is when the characters that know an entry learned it: 0 at the start, the story's turn when a lorebook is added later. */
1913
+ function populateLore(session, definitions, turn = 0) {
1914
+ for (const entry of definitions) session.lore.add({
1915
+ sourceId: entry.id,
1916
+ title: entry.title,
1917
+ kind: entry.kind,
1918
+ scope: entry.scope,
1919
+ summary: entry.summary,
1920
+ body: entry.body,
1921
+ ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
1922
+ ...entry.endsAt === void 0 ? {} : { endsAt: entry.endsAt },
1923
+ subjects: [],
1924
+ related: [],
1925
+ sources: entry.sources
1926
+ });
1927
+ const subject = (wanted) => ({
1928
+ kind: wanted.kind,
1929
+ id: wanted.kind === "character" ? session.characters.getBySourceId(wanted.id).id : wanted.kind === "faction" ? session.factions.getBySourceId(wanted.id).id : wanted.kind === "location" ? session.locations.getBySourceId(wanted.id).id : wanted.kind === "item" ? session.items.getBySourceId(wanted.id).id : session.lore.getBySourceId(wanted.id).id
1930
+ });
1931
+ for (const entry of definitions) session.lore.update(session.lore.getBySourceId(entry.id).id, {
1932
+ subjects: entry.subjects.map(subject),
1933
+ related: entry.related.map((id) => session.lore.getBySourceId(id).id)
1934
+ });
1935
+ for (const entry of definitions) {
1936
+ const lore = session.lore.getBySourceId(entry.id);
1937
+ for (const reference of entry.knownBy) {
1938
+ const knower = session.characters.getBySourceId(reference) ?? session.characters.findByName(reference)[0];
1939
+ if (knower !== void 0) session.knowledge.learn(knower.id, "lore", lore.id, turn);
1940
+ }
1941
+ }
1942
+ }
1943
+ /** What is wrong with where the characters start, found before anything is created. */
1944
+ function startingPlaceProblems(characters, locations) {
1945
+ const byId = new Map(locations.map((location) => [location.id, location]));
1946
+ return characters.flatMap((character) => {
1947
+ const place = character.start.place;
1948
+ if (place === void 0) return [];
1949
+ const location = byId.get(place.location);
1950
+ if (location === void 0) return [`${character.id}: start.location "${place.location}" is not a place of this world`];
1951
+ if (place.feature !== void 0 && !location.features.some((feature) => feature.key === place.feature)) return [`${character.id}: start.feature "${place.feature}" is not a feature of ${location.name} (it has: ${location.features.map((feature) => feature.key).join(", ") || "none"})`];
1952
+ return [];
1953
+ });
1954
+ }
1955
+ /** Declare what the world tracks and give everything the values it starts with. */
1956
+ function populateVariables(session, defs, world) {
1957
+ for (const def of defs) session.variables.define(def);
1958
+ const give = (kind, id, values) => {
1959
+ for (const [key, value] of Object.entries(values ?? {})) session.variables.set(key, kind, id, { value }, 0);
1960
+ };
1961
+ for (const entry of world.characters) give("character", session.characters.getBySourceId(entry.id).id, entry.variables);
1962
+ for (const entry of world.items) give("item", session.items.getBySourceId(entry.id).id, entry.variables);
1963
+ for (const entry of world.locations) give("location", session.locations.getBySourceId(entry.id).id, entry.variables);
1964
+ give("world", 0, world.values);
1965
+ }
1966
+ /** What is wrong with the days characters are given, found before anything is created: places that are not in the world. */
1967
+ function routineProblems(characters, locations, calendar) {
1968
+ calendar ??= {
1969
+ hemisphere: "north",
1970
+ holidays: []
1971
+ };
1972
+ const byId = new Map(locations.map((location) => [location.id, location]));
1973
+ const holidays = new Set(calendar.holidays.map((holiday) => holiday.id));
1974
+ return characters.flatMap((character) => (character.routine ?? []).flatMap((window, index) => {
1975
+ const days = dayTokenProblems(window.on ?? [], `${character.id}: routine[${index}].on`, holidays);
1976
+ if (days.length > 0) return days;
1977
+ if (window.location === void 0) return [];
1978
+ const location = byId.get(window.location);
1979
+ if (location === void 0) return [`${character.id}: routine[${index}].location "${window.location}" is not a place of this world`];
1980
+ if (window.feature !== void 0 && !location.features.some((feature) => feature.key === window.feature)) return [`${character.id}: routine[${index}].feature "${window.feature}" is not a feature of ${location.name}`];
1981
+ return [];
1982
+ }));
1983
+ }
1984
+ /** Keeps the checks of the world with the story: what its game master rolls and how the dice are read. */
1985
+ function populateDice(session, checks) {
1986
+ for (const check of checks) session.dice.define(check);
1987
+ }
1988
+ /** Keeps the world's calendar with the story, for the days a routine or a trigger waits for. */
1989
+ function populateCalendar(session, calendar) {
1990
+ if (calendar.holidays.length > 0 || calendar.hemisphere !== "north") writeCalendar(session.metadata, calendar);
1991
+ }
1992
+ /** Gives each character its recurring day, with the places by their ids in the world. */
1993
+ function populateRoutines(session, characters) {
1994
+ for (const { id, routine } of characters) {
1995
+ if (routine === void 0 || routine.length === 0) continue;
1996
+ session.routines.replace(session.characters.getBySourceId(id).id, routine.map((window) => ({
1997
+ days: window.days.map((day) => WEEKDAY_NAMES.indexOf(day)),
1998
+ on: window.on ?? [],
1999
+ start: parseTimeOfDay(window.from),
2000
+ end: parseTimeOfDay(window.to),
2001
+ activity: window.activity,
2002
+ interruptible: window.interruptible,
2003
+ ...window.sleep === true ? { sleep: true } : {},
2004
+ ...window.location === void 0 ? {} : { locationId: session.locations.getBySourceId(window.location).id },
2005
+ ...window.feature === void 0 ? {} : { featureKey: window.feature },
2006
+ ...window.position === void 0 ? {} : { position: window.position }
2007
+ })));
2008
+ }
2009
+ }
2010
+ /** Put a world's places into a new session: each inside the one it belongs to, with the ways between them (both ways unless the file says one way). */
2011
+ function populateLocations(session, locations) {
2012
+ const ordered = parentsFirst(locations);
2013
+ for (const { id, name, description, parent, features, visualIdentity } of ordered) {
2014
+ const parentId = parent === void 0 ? void 0 : session.locations.getBySourceId(parent)?.id;
2015
+ const stored = session.locations.add({
2016
+ sourceId: id,
2017
+ name,
2018
+ description,
2019
+ features,
2020
+ ...parentId === void 0 ? {} : { parentId }
2021
+ });
2022
+ if (visualIdentity !== void 0) session.visualIdentities.set("location", stored.id, visualIdentity);
2023
+ }
2024
+ for (const location of ordered) {
2025
+ const from = session.locations.getBySourceId(location.id);
2026
+ for (const exit of location.exits) {
2027
+ const to = session.locations.getBySourceId(exit.to);
2028
+ const shared = {
2029
+ ...exit.travelSeconds === void 0 ? {} : { travelSeconds: exit.travelSeconds },
2030
+ state: exit.state,
2031
+ note: exit.note
2032
+ };
2033
+ if (session.locations.getExit(from.id, to.id) === void 0) session.locations.addExit({
2034
+ fromId: from.id,
2035
+ toId: to.id,
2036
+ description: exit.description,
2037
+ ...shared
2038
+ });
2039
+ if (!exit.oneWay && session.locations.getExit(to.id, from.id) === void 0) session.locations.addExit({
2040
+ fromId: to.id,
2041
+ toId: from.id,
2042
+ description: exit.backDescription ?? exit.description,
2043
+ ...shared
2044
+ });
2045
+ }
2046
+ }
2047
+ }
2048
+ /**
2049
+ * Put a world's cast into a new session: each character with the state it
2050
+ * starts in and its intents. The player controls the character whose world id
2051
+ * is `playerId`; the agent controls everyone else.
2052
+ */
2053
+ function populateCharacters(session, characters, playerId) {
2054
+ for (const { id, start, relationships: _relationships, knowledge: _knowledge, routine: _routine, visualIdentity, ...identity } of characters) {
2055
+ const character = session.characters.add({
2056
+ ...identity,
2057
+ sourceId: id,
2058
+ control: id === playerId ? "player" : "agent"
2059
+ });
2060
+ if (visualIdentity !== void 0) session.visualIdentities.set("character", character.id, visualIdentity);
2061
+ const { intents, place, emotion, ...state } = start;
2062
+ session.characterStates.create(character.id, state);
2063
+ if (emotion !== void 0) for (const axis of [
2064
+ "valence",
2065
+ "arousal",
2066
+ "dominance"
2067
+ ]) session.variables.set(axis, "character", character.id, {
2068
+ value: emotion.immediate[axis],
2069
+ baseline: emotion.baseline[axis]
2070
+ }, 0);
2071
+ for (const intent of intents) session.intents.add(character.id, intent);
2072
+ if (place !== void 0) {
2073
+ const location = session.locations.getBySourceId(place.location);
2074
+ session.placements.place("character", character.id, {
2075
+ locationId: location.id,
2076
+ ...place.position === void 0 ? {} : { position: place.position },
2077
+ ...place.feature === void 0 ? {} : { featureKey: place.feature }
2078
+ });
2079
+ }
2080
+ }
2081
+ for (const { id, relationships } of characters) {
2082
+ const from = session.characters.getBySourceId(id);
2083
+ for (const relation of relationships ?? []) session.relationships.upsert(from.id, session.characters.getBySourceId(relation.to).id, {
2084
+ label: relation.label,
2085
+ summary: relation.summary,
2086
+ familiarity: relation.familiarity,
2087
+ trust: relation.trust,
2088
+ affinity: relation.affinity,
2089
+ tension: relation.tension
2090
+ }, 0);
2091
+ }
2179
2092
  }
2180
- /** 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. */
2181
- function originOf(card, choices, pieces, records, name, items = itemise(card, choices)) {
2182
- if (records.roster === void 0 || records.classified === void 0) return [];
2183
- const entity = findEntity(records.roster, name);
2184
- if (entity === void 0) return [];
2185
- const names = [entity.name, ...entity.aliases].map(norm);
2186
- const chosen = sourcesFor(entity, items, records.classified);
2187
- const about = (id) => (records.classified?.[id]?.targets ?? []).some((target) => target.kind === entity.kind && names.includes(norm(target.name)));
2188
- const seen = /* @__PURE__ */ new Set();
2189
- return chosen.flatMap((item) => {
2190
- const id = baseId(item.id);
2191
- const piece = pieces.find((entry) => entry.id === id);
2192
- if (piece === void 0 || seen.has(id)) return [];
2193
- seen.add(id);
2194
- return [{
2195
- piece: id,
2196
- label: piece.label,
2197
- how: about(item.id) ? "about it" : "mentions it"
2198
- }];
2199
- });
2093
+ function populateFactions(session, factions) {
2094
+ for (const definition of factions) {
2095
+ const faction = session.factions.add({
2096
+ sourceId: definition.id,
2097
+ name: definition.name,
2098
+ aliases: definition.aliases,
2099
+ summary: definition.summary,
2100
+ description: definition.description,
2101
+ values: definition.values,
2102
+ structure: definition.structure
2103
+ });
2104
+ session.factionStates.create(faction.id, definition.start);
2105
+ for (const goal of definition.start.goals) session.factionIntents.add(faction.id, goal);
2106
+ }
2107
+ for (const definition of factions) {
2108
+ const faction = session.factions.getBySourceId(definition.id);
2109
+ for (const member of definition.members) {
2110
+ const character = session.characters.getBySourceId(member.character);
2111
+ session.factionMemberships.upsert(faction.id, character.id, member, 0);
2112
+ if (session.factionRelationships.get("character", character.id, "faction", faction.id) === void 0) session.factionRelationships.upsert("character", character.id, "faction", faction.id, {
2113
+ label: member.role || "member",
2114
+ familiarity: 1
2115
+ }, 0);
2116
+ }
2117
+ for (const relation of definition.relationships) {
2118
+ const target = relation.to.kind === "character" ? session.characters.getBySourceId(relation.to.id) : session.factions.getBySourceId(relation.to.id);
2119
+ session.factionRelationships.upsert("faction", faction.id, relation.to.kind, target.id, relation, 0);
2120
+ }
2121
+ }
2200
2122
  }
2201
- // src/host/import/repair.ts
2202
- const ENTITY_FILE = /^(characters|locations|factions|items|lore)\/[^/]+\/(character|location|faction|item|lore)\.json$/;
2203
- /** Fields a document cannot do without, and fields that tie it to others: never dropped, whatever the problem says. */
2204
- const KEPT = /* @__PURE__ */ new Set([
2205
- "id",
2206
- "name",
2207
- "role",
2208
- "kind",
2209
- "tier",
2210
- "from",
2211
- "to",
2212
- "parent",
2213
- "summary"
2214
- ]);
2215
- const ABOUT_VALUE = /^(must be|is longer than|has more than|is not one of|must not|cannot be)/;
2216
- const STEP = /([^.[\]]+)|\[(\d+)\]/g;
2217
- const stepsOf = (field) => [...field.matchAll(STEP)].map((match) => match[2] === void 0 ? match[1] : Number(match[2]));
2218
- /** Removes what `steps` names; false when it is not there. */
2219
- function remove(root, steps) {
2220
- let at = root;
2221
- for (const step of steps.slice(0, -1)) {
2222
- at = at?.[step];
2223
- if (typeof at !== "object" || at === null) return void 0;
2123
+ /** Give each character its authored knowledge, plus what is visible where it starts. */
2124
+ function populateKnowledge(session, characters) {
2125
+ for (const definition of characters) {
2126
+ const character = session.characters.getBySourceId(definition.id);
2127
+ for (const key of definition.knowledge?.locations ?? []) session.knowledge.learn(character.id, "location", session.locations.getBySourceId(key).id, 0);
2128
+ for (const key of definition.knowledge?.items ?? []) session.knowledge.learn(character.id, "item", session.items.getBySourceId(key).id, 0);
2129
+ for (const wanted of definition.knowledge?.exits ?? []) {
2130
+ const exit = session.locations.getExit(session.locations.getBySourceId(wanted.from).id, session.locations.getBySourceId(wanted.to).id);
2131
+ session.knowledge.learn(character.id, "exit", exit.id, 0);
2132
+ session.knowledge.learn(character.id, "location", exit.fromId, 0);
2133
+ session.knowledge.learn(character.id, "location", exit.toId, 0);
2134
+ }
2135
+ for (const key of definition.knowledge?.lore ?? []) session.knowledge.learn(character.id, "lore", session.lore.getBySourceId(key).id, 0);
2136
+ const placement = session.placements.get("character", character.id);
2137
+ if (placement === void 0) continue;
2138
+ session.knowledge.learn(character.id, "location", placement.locationId, 0, true);
2139
+ for (const exit of session.locations.exitsFrom(placement.locationId)) {
2140
+ session.knowledge.learn(character.id, "exit", exit.id, 0, true);
2141
+ session.knowledge.learn(character.id, "location", exit.toId, 0);
2142
+ }
2143
+ for (const { item } of session.items.contents({
2144
+ kind: "location",
2145
+ id: placement.locationId
2146
+ })) if (!item.hidden) session.knowledge.learn(character.id, "item", item.id, 0, true);
2147
+ for (const { item } of session.items.contents({
2148
+ kind: "character",
2149
+ id: character.id
2150
+ })) session.knowledge.learn(character.id, "item", item.id, 0, true);
2151
+ for (const other of session.placements.at(placement.locationId, "character")) if (other.entityId !== character.id && session.relationships.get(character.id, other.entityId) === void 0) session.relationships.upsert(character.id, other.entityId, { label: "acquaintance" }, 0);
2224
2152
  }
2225
- const last = steps.at(-1);
2226
- if (typeof at !== "object" || at === null || !(last in at)) return void 0;
2227
- const value = at[last];
2228
- if (Array.isArray(at) && typeof last === "number") at.splice(last, 1);
2229
- else delete at[last];
2230
- return { value };
2231
2153
  }
2232
2154
  /**
2233
- * Mends what the world check refused, one field at a time and only where that is safe: an optional field of an entity whose value cannot be used (wrong type, too long, not one of the
2234
- * allowed words) is dropped. A missing required field, a name, an id or a link to another entity is never touched: those stay problems for a person or the assistant. Returns what was dropped, with the values.
2155
+ * Put a world's slots and things into a new session, each where it starts, with what opens each lock. Containers come
2156
+ * before what is in them; what opens an exit is set for both directions of it.
2235
2157
  */
2236
- async function repairFields(directory, problems) {
2237
- const repairs = [];
2238
- const byFile = /* @__PURE__ */ new Map();
2239
- for (const problem of problems) {
2240
- if (!ENTITY_FILE.test(problem.where)) continue;
2241
- const split = problem.message.indexOf(": ");
2242
- if (split < 0) continue;
2243
- const field = problem.message.slice(0, split);
2244
- const because = problem.message.slice(split + 2);
2245
- if (!/^[\w.[\]]+$/.test(field) || !ABOUT_VALUE.test(because) || KEPT.has(stepsOf(field)[0])) continue;
2246
- byFile.set(problem.where, [...byFile.get(problem.where) ?? [], {
2247
- field,
2248
- because
2249
- }]);
2158
+ function populateItems(session, items, slots, locations) {
2159
+ for (const slot of slots) session.slots.upsert(slot);
2160
+ const made = /* @__PURE__ */ new Map();
2161
+ for (const definition of containersFirst(items)) {
2162
+ const { start } = definition;
2163
+ const holder = start.kind === "location" ? {
2164
+ kind: "location",
2165
+ locationId: session.locations.getBySourceId(start.location).id,
2166
+ ...start.position === void 0 ? {} : { position: start.position },
2167
+ ...start.feature === void 0 ? {} : { featureKey: start.feature }
2168
+ } : start.kind === "held" ? {
2169
+ kind: "character",
2170
+ characterId: session.characters.getBySourceId(start.character).id,
2171
+ mode: "held"
2172
+ } : start.kind === "worn" ? {
2173
+ kind: "character",
2174
+ characterId: session.characters.getBySourceId(start.character).id,
2175
+ mode: "worn",
2176
+ slot: definition.wearable,
2177
+ ...start.position === void 0 ? {} : { position: start.position }
2178
+ } : {
2179
+ kind: "item",
2180
+ itemId: made.get(start.item),
2181
+ ...start.position === void 0 ? {} : { position: start.position }
2182
+ };
2183
+ const item = session.items.add({
2184
+ sourceId: definition.id,
2185
+ name: definition.name,
2186
+ description: definition.description,
2187
+ quantity: definition.quantity,
2188
+ unique: definition.unique,
2189
+ quality: definition.quality,
2190
+ notable: definition.notable,
2191
+ hidden: definition.hidden,
2192
+ ...definition.wearable === void 0 ? {} : { wearableSlot: definition.wearable },
2193
+ ...definition.container === void 0 ? {} : { container: { state: definition.container.state } },
2194
+ ...definition.owner === void 0 ? {} : { ownerId: session.characters.getBySourceId(definition.owner).id }
2195
+ }, holder);
2196
+ if (definition.visualIdentity !== void 0) session.visualIdentities.set("item", item.id, definition.visualIdentity);
2197
+ made.set(definition.id, item.id);
2250
2198
  }
2251
- for (const [file, fields] of byFile) {
2252
- const document = JSON.parse(await readFile(join(directory, file), "utf8"));
2253
- for (const { field, because } of fields.sort((a, b) => b.field.localeCompare(a.field, void 0, { numeric: true }))) {
2254
- const dropped = remove(document, stepsOf(field));
2255
- if (dropped !== void 0) repairs.push({
2256
- file,
2257
- field,
2258
- value: dropped.value,
2259
- because
2260
- });
2199
+ for (const definition of items) if (definition.container !== void 0 && definition.container.openedBy.length > 0) session.items.setOpeners({
2200
+ kind: "item",
2201
+ id: made.get(definition.id)
2202
+ }, definition.container.openedBy.map((key) => made.get(key)));
2203
+ for (const place of locations) {
2204
+ const from = session.locations.getBySourceId(place.id);
2205
+ for (const exit of place.exits) {
2206
+ if ((exit.openedBy ?? []).length === 0) continue;
2207
+ const to = session.locations.getBySourceId(exit.to);
2208
+ for (const [a, b] of [[from.id, to.id], [to.id, from.id]]) {
2209
+ const way = session.locations.getExit(a, b);
2210
+ if (way !== void 0) session.items.setOpeners({
2211
+ kind: "exit",
2212
+ id: way.id
2213
+ }, exit.openedBy.map((key) => made.get(key)));
2214
+ }
2215
+ }
2216
+ }
2217
+ }
2218
+ /** Starts the story's clock: at the wall clock when it follows it, and otherwise at the world's starting time (or now, when the world has none). */
2219
+ function populateClock(session, settings, world, wall) {
2220
+ const start = settings.mode === "real" ? wall : world?.startingTime ?? Math.floor(wall / MINUTE) * MINUTE;
2221
+ session.clock.start(settings.mode, start);
2222
+ }
2223
+ /**
2224
+ * Make the world's triggers, once everything they can name exists.
2225
+ * @throws {Error} naming each trigger that names something the world does not have.
2226
+ */
2227
+ function populateTriggers(session, definitions) {
2228
+ const keys = definitions.map((definition) => definition.key);
2229
+ const problems = definitions.flatMap((definition) => triggerReferenceProblems(session, definition, keys));
2230
+ if (problems.length > 0) throw new InvalidWorldError(`the triggers have ${problems.length} problem(s)`, problems.map((message) => ({
2231
+ path: TRIGGERS_FILE_NAME,
2232
+ message
2233
+ })));
2234
+ for (const definition of definitions) session.triggers.add(definition, "world", 0);
2235
+ }
2236
+ // src/host/worlds/scratch.ts
2237
+ /**
2238
+ * 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
2239
+ * a store has; the search a session adds is not needed.
2240
+ */
2241
+ function withScratchStory(parts, use) {
2242
+ const scratch = createSessionStore(":memory:", {
2243
+ id: "scratch",
2244
+ name: "scratch",
2245
+ world: {
2246
+ id: "scratch",
2247
+ name: "scratch"
2261
2248
  }
2262
- if (repairs.some((repair) => repair.file === file)) await atomicWrite(join(directory, file), `${JSON.stringify(document, null, 2)}\n`);
2249
+ }, { vectors: false });
2250
+ try {
2251
+ const session = scratch;
2252
+ if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
2253
+ populateLocations(session, parts.locations);
2254
+ populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
2255
+ populateItems(session, parts.items, parts.slots, parts.locations);
2256
+ populateVariables(session, parts.variables, {
2257
+ characters: parts.characters,
2258
+ items: parts.items,
2259
+ locations: parts.locations,
2260
+ values: void 0
2261
+ });
2262
+ return use(session);
2263
+ } finally {
2264
+ scratch.close();
2263
2265
  }
2264
- return repairs;
2265
2266
  }
2266
- // src/host/worlds/world-file-io.ts
2267
- const queue = new SerialQueue();
2267
+ // src/host/worlds/validated-world.ts
2268
2268
  /**
2269
- * Runs `work` after everything asked for the same folder before it has finished. The import, the editor and the assistant each read `world.json`, change a field and write it
2270
- * back; run side by side, the last one to write would take back what the others changed.
2269
+ * Reads everything a world's files hold and checks it all as a session start does: every file reads, and what refers to something refers to something that is there.
2270
+ * @throws {InvalidWorldError} naming every problem of the first part of the world that has any.
2271
2271
  */
2272
- function serialized(directory, work) {
2273
- return queue.run(directory, work);
2274
- }
2275
- /** Changes `world.json` in place: read, `update`, written back in one step with the indentation the file had, nothing else moving in between. @returns the document as written. */
2276
- function updateWorldFile(directory, update) {
2277
- return serialized(directory, async () => {
2278
- const file = join(directory, WORLD_FILE_NAME);
2279
- const text = await readFile(file, "utf8");
2280
- const document = JSON.parse(text.replace(/^/, ""));
2281
- await update(document);
2282
- await atomicWrite(file, JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") || text.trim() === "" ? "\n" : ""));
2283
- return document;
2272
+ async function loadValidatedWorld(world) {
2273
+ const { characters, problems } = await loadCharacters(world.directory);
2274
+ if (problems.length > 0) throw new InvalidWorldError(`the characters of "${world.summary.name}" have ${problems.length} problem(s)`, problems);
2275
+ const { factions, problems: factionFileProblems } = await loadFactions(world.directory);
2276
+ if (factionFileProblems.length > 0) throw new InvalidWorldError(`the factions of "${world.summary.name}" have ${factionFileProblems.length} problem(s)`, factionFileProblems);
2277
+ const factionReferences = factionProblems(factions, characters);
2278
+ if (factionReferences.length > 0) throw new InvalidWorldError(`the factions of "${world.summary.name}" have ${factionReferences.length} problem(s)`, factionReferences.map((message) => ({
2279
+ path: world.directory,
2280
+ message
2281
+ })));
2282
+ const { locations, problems: locationProblems } = await loadLocations(world.directory);
2283
+ if (locationProblems.length > 0) throw new InvalidWorldError(`the places of "${world.summary.name}" have ${locationProblems.length} problem(s)`, locationProblems);
2284
+ const placing = startingPlaceProblems(characters, locations);
2285
+ if (placing.length > 0) throw new InvalidWorldError(`the starting places of "${world.summary.name}" have ${placing.length} problem(s)`, placing.map((message) => ({
2286
+ path: world.directory,
2287
+ message
2288
+ })));
2289
+ const { calendar, problems: calendarProblems } = await loadCalendar(world.directory);
2290
+ if (calendarProblems.length > 0) throw new InvalidWorldError(`the calendar of "${world.summary.name}" has ${calendarProblems.length} problem(s)`, calendarProblems);
2291
+ const dice = await loadDice(world.directory);
2292
+ if (dice.problems.length > 0) throw new InvalidWorldError(`the dice checks of "${world.summary.name}" have ${dice.problems.length} problem(s)`, dice.problems);
2293
+ const days = routineProblems(characters, locations, calendar);
2294
+ if (days.length > 0) throw new InvalidWorldError(`the days of the characters of "${world.summary.name}" have ${days.length} problem(s)`, days.map((message) => ({
2295
+ path: world.directory,
2296
+ message
2297
+ })));
2298
+ const { items, slots, problems: itemProblems } = await loadItems(world.directory, {
2299
+ characters: characters.map((character) => character.id),
2300
+ locations
2301
+ });
2302
+ if (itemProblems.length > 0) throw new InvalidWorldError(`the items of "${world.summary.name}" have ${itemProblems.length} problem(s)`, itemProblems);
2303
+ const authoredLore = await loadLore(world.directory);
2304
+ if (authoredLore.problems.length > 0) throw new InvalidWorldError(`the lore of "${world.summary.name}" has ${authoredLore.problems.length} problem(s)`, authoredLore.problems);
2305
+ const loreReferences = loreProblems(authoredLore.lore, {
2306
+ characters,
2307
+ factions,
2308
+ locations,
2309
+ items
2310
+ });
2311
+ if (loreReferences.length > 0) throw new InvalidWorldError(`the lore of "${world.summary.name}" has ${loreReferences.length} invalid reference(s)`, loreReferences.map((message) => ({
2312
+ path: world.directory,
2313
+ message
2314
+ })));
2315
+ const knowing = knowledgeProblems(characters, locations, items, authoredLore.lore);
2316
+ if (knowing.length > 0) throw new InvalidWorldError(`the starting knowledge of "${world.summary.name}" has ${knowing.length} problem(s)`, knowing.map((message) => ({
2317
+ path: world.directory,
2318
+ message
2319
+ })));
2320
+ const declared = await loadVariables(world.directory);
2321
+ if (declared.problems.length > 0) throw new InvalidWorldError(`the variables of "${world.summary.name}" have ${declared.problems.length} problem(s)`, declared.problems);
2322
+ const commandFile = await loadCommands(world.directory);
2323
+ if (commandFile.problems.length > 0) throw new InvalidWorldError(`the commands of "${world.summary.name}" have ${commandFile.problems.length} problem(s)`, commandFile.problems);
2324
+ const own = new Set(declared.defs.map((def) => def.key));
2325
+ const clashing = commandFile.commands.filter((command) => own.has(commandVariable(command)));
2326
+ if (clashing.length > 0) throw new InvalidWorldError(`the commands of "${world.summary.name}" have ${clashing.length} problem(s)`, clashing.map((command) => ({
2327
+ path: world.directory,
2328
+ message: `/${command.word} raises the flag ${commandVariable(command)}, which variables.json declares too: remove one`
2329
+ })));
2330
+ declared.defs = [...declared.defs, ...commandFile.commands.map(commandFlag)];
2331
+ const tracking = variableProblems({
2332
+ defs: declared.defs,
2333
+ characters,
2334
+ items,
2335
+ locations,
2336
+ values: world.variables
2337
+ });
2338
+ if (tracking.length > 0) throw new InvalidWorldError(`what "${world.summary.name}" tracks has ${tracking.length} problem(s)`, tracking.map((message) => ({
2339
+ path: world.directory,
2340
+ message
2341
+ })));
2342
+ const scripted = await loadTriggers(world.directory);
2343
+ if (scripted.problems.length > 0) throw new InvalidWorldError(`the triggers of "${world.summary.name}" have ${scripted.problems.length} problem(s)`, scripted.problems);
2344
+ const authoredPlots = await loadPlots(world.directory);
2345
+ if (authoredPlots.problems.length > 0) throw new InvalidWorldError(`the plots of "${world.summary.name}" have ${authoredPlots.problems.length} problem(s)`, authoredPlots.problems);
2346
+ const plotReferences = plotReferenceProblems(authoredPlots.plots, [
2347
+ ...characters.map((entry) => entry.id),
2348
+ ...factions.map((entry) => entry.id),
2349
+ ...locations.map((entry) => entry.id),
2350
+ ...items.map((entry) => entry.id),
2351
+ ...authoredLore.lore.map((entry) => entry.id)
2352
+ ]);
2353
+ if (plotReferences.length > 0) throw new InvalidWorldError(`the plots of "${world.summary.name}" have ${plotReferences.length} invalid participant(s)`, plotReferences.map((message) => ({
2354
+ path: world.directory,
2355
+ message
2356
+ })));
2357
+ const related = relationshipProblems(characters);
2358
+ if (related.length > 0) throw new InvalidWorldError(`the relationships of "${world.summary.name}" have ${related.length} problem(s)`, related.map((message) => ({
2359
+ path: world.directory,
2360
+ message
2361
+ })));
2362
+ withScratchStory({
2363
+ characters,
2364
+ locations,
2365
+ items,
2366
+ slots,
2367
+ variables: declared.defs,
2368
+ calendar
2369
+ }, (story) => {
2370
+ populateTriggers(story, scripted.triggers);
2284
2371
  });
2372
+ return {
2373
+ characters,
2374
+ factions,
2375
+ locations,
2376
+ items,
2377
+ slots,
2378
+ authoredLore,
2379
+ declared,
2380
+ scripted,
2381
+ authoredPlots,
2382
+ calendar,
2383
+ checks: dice.checks,
2384
+ commands: commandFile.commands
2385
+ };
2386
+ }
2387
+ // src/host/worlds/world-check.ts
2388
+ /** The most problems listed at once: the rest are named by their number. */
2389
+ const LISTED$1 = 40;
2390
+ /**
2391
+ * 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
2392
+ * 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
2393
+ * fixing those can show the next part's.
2394
+ */
2395
+ async function checkWorld(world) {
2396
+ try {
2397
+ await loadValidatedWorld(world);
2398
+ return {
2399
+ ok: true,
2400
+ problems: [],
2401
+ more: 0
2402
+ };
2403
+ } catch (error) {
2404
+ if (!(error instanceof InvalidWorldError)) throw error;
2405
+ const problems = error.problems.map((problem) => ({
2406
+ where: relative(world.directory, problem.path).split(sep).join("/") || "(the world)",
2407
+ message: problem.message
2408
+ }));
2409
+ return {
2410
+ ok: false,
2411
+ summary: error.message,
2412
+ problems: problems.slice(0, LISTED$1),
2413
+ more: Math.max(0, problems.length - LISTED$1)
2414
+ };
2415
+ }
2285
2416
  }
2286
2417
  // src/host/worlds/entity-folders.ts
2287
2418
  /** 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. */
@@ -2317,21 +2448,33 @@ const STAGE = "stage";
2317
2448
  const MAX_DESCRIPTION = 500;
2318
2449
  const MAX_TAGS = 8;
2319
2450
  const MAX_TAG = 30;
2320
- /** The card's other greetings, as the other openings a player may start with: the first message and the alternates that were not chosen. */
2451
+ /** A title for an opening taken from a card: its first words, so the start dialog shows what the story begins with. */
2452
+ function openingTitle(text) {
2453
+ const first = text.trim().split("\n")[0].replace(/\s+/g, " ");
2454
+ if (first.length <= 40) return first;
2455
+ const cut = first.slice(0, 40);
2456
+ const space = cut.lastIndexOf(" ");
2457
+ return `${(space > 15 ? cut.slice(0, space) : cut).replace(/[,;:.\s]+$/, "")}…`;
2458
+ }
2459
+ /** The card's other greetings, as the other openings a player may start with: the first message and the alternates that were not chosen, each titled by its first words. */
2321
2460
  function alternateOpenings(card, chosen, player) {
2322
2461
  if (chosen.kind === "none") return [];
2323
- return [{
2324
- title: "First message",
2462
+ const greetings = [{
2325
2463
  text: card.firstMessage,
2326
2464
  taken: chosen.kind === "first"
2327
2465
  }, ...card.alternateGreetings.map((text, index) => ({
2328
- title: `Alternate ${index + 1}`,
2329
2466
  text,
2330
2467
  taken: chosen.kind === "alternate" && chosen.index === index
2331
- }))].flatMap(({ title, text, taken }) => {
2468
+ }))];
2469
+ const used = /* @__PURE__ */ new Map();
2470
+ return greetings.flatMap(({ text, taken }) => {
2332
2471
  const cleaned = taken || text.trim() === "" ? "" : openingMessage(text, card.name, player);
2333
- return cleaned === "" || cleaned.length > 2e4 ? [] : [{
2334
- title,
2472
+ if (cleaned === "" || cleaned.length > MAX_OPENING_CHARS) return [];
2473
+ const base = openingTitle(cleaned);
2474
+ const seen = used.get(base) ?? 0;
2475
+ used.set(base, seen + 1);
2476
+ return [{
2477
+ title: seen === 0 ? base : `${base} (${seen + 1})`,
2335
2478
  text: cleaned
2336
2479
  }];
2337
2480
  }).slice(0, 30);
@@ -2618,7 +2761,23 @@ async function finishImport(ctx, input) {
2618
2761
  })}\n`);
2619
2762
  cover = true;
2620
2763
  }
2621
- const alternates = alternateOpenings(card, choices.opening, player === void 0 ? void 0 : String(player["name"]));
2764
+ const openingPlayer = player === void 0 ? void 0 : String(player["name"]);
2765
+ const speakers = extracted.characters.map((document) => ({
2766
+ id: String(document["id"]),
2767
+ name: String(document["name"]),
2768
+ aliases: Array.isArray(document["aliases"]) ? document["aliases"].filter((alias) => typeof alias === "string") : []
2769
+ }));
2770
+ const playerId = player === void 0 ? void 0 : String(player["id"]);
2771
+ const shapedMain = opening === void 0 ? void 0 : await shapeOpening(ctx, openingMessage(opening, card.name, openingPlayer), speakers, playerId);
2772
+ const shapedAlternates = await mapLimit(alternateOpenings(card, choices.opening, openingPlayer), ctx.concurrency, async (entry) => ({
2773
+ title: entry.title,
2774
+ shaped: await shapeOpening(ctx, entry.text, speakers, playerId)
2775
+ }));
2776
+ const alternates = shapedAlternates.map(({ title, shaped }) => ({
2777
+ title,
2778
+ ...shaped.parts === void 0 ? { text: shaped.text } : { parts: shaped.parts }
2779
+ }));
2780
+ for (const note of [shapedMain?.note, ...shapedAlternates.map((entry) => entry.shaped.note)]) if (note !== void 0) notes.push(note);
2622
2781
  await updateWorldFile(directory, (world) => {
2623
2782
  world["description"] = described.description;
2624
2783
  if (described.startingTime !== void 0 && world["starting_time"] === void 0) world["starting_time"] = described.startingTime;
@@ -2626,7 +2785,7 @@ async function finishImport(ctx, input) {
2626
2785
  ...typeof world["metadata"] === "object" && world["metadata"] !== null ? world["metadata"] : {},
2627
2786
  tags: described.tags
2628
2787
  };
2629
- if (opening !== void 0) world["opening_message"] = openingMessage(opening, card.name, player === void 0 ? void 0 : String(player["name"]));
2788
+ if (shapedMain !== void 0) world["opening_message"] = shapedMain.parts ?? shapedMain.text;
2630
2789
  if (alternates.length > 0) world["alternate_openings"] = alternates;
2631
2790
  if (extracted.rules.length > 0 && world["rules"] === void 0) world["rules"] = extracted.rules.slice(0, 30);
2632
2791
  if (card.creator.trim() !== "" && world["author"] === void 0) world["author"] = { name: card.creator.trim() };
@@ -3234,6 +3393,15 @@ const CHECK_COMMANDS = {
3234
3393
  "check-play": ["playability"]
3235
3394
  };
3236
3395
  const findingKey = (finding) => `${finding.check}\n${finding.code}\n${finding.where}\n${finding.message}`;
3396
+ /** How the check commands are described where commands are listed. Add `deep` after the name to let the model judge too, and anything else to say what to look at. */
3397
+ const CHECK_COMMAND_DESCRIPTIONS = {
3398
+ check: "Check the world with every kit of checks",
3399
+ "check-all": "Check the world with every kit of checks",
3400
+ "check-world": "Check that the world agrees with itself",
3401
+ "check-card": "Check that the world carries what the imported card says",
3402
+ "check-quality": "Check the quality of the world: panels, style, leftovers",
3403
+ "check-play": "Check that the world can be played"
3404
+ };
3237
3405
  // src/host/checks/terms.ts
3238
3406
  const HAN = /[㐀-鿿]+/gu;
3239
3407
  /** Words of fewer letters are mostly the glue of a language, which says nothing about whether two texts share facts. */
@@ -3375,10 +3543,33 @@ const toolsOf = (value) => {
3375
3543
  const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
3376
3544
  return typeof board === "string" ? {} : board;
3377
3545
  };
3546
+ /** The parts of an opening as the file has them; parts that cannot be read are left out. */
3547
+ function partsOf(list) {
3548
+ const parts = parseOpeningParts(list, "opening", []);
3549
+ return parts === void 0 || parts.length === 0 ? void 0 : parts;
3550
+ }
3551
+ function alternateOf(entry) {
3552
+ if (typeof entry !== "object" || entry === null) return [];
3553
+ const body = entry;
3554
+ const character = textOf(body["character"]);
3555
+ const named = character === "" ? {} : { character };
3556
+ const parts = Array.isArray(body["parts"]) ? partsOf(body["parts"]) : void 0;
3557
+ if (parts !== void 0) return [{
3558
+ title: textOf(body["title"]),
3559
+ text: partsText(parts),
3560
+ parts,
3561
+ ...named
3562
+ }];
3563
+ return typeof body["text"] === "string" ? [{
3564
+ title: textOf(body["title"]),
3565
+ text: body["text"],
3566
+ ...named
3567
+ }] : [];
3568
+ }
3378
3569
  function infoOf(document, startQuestions = []) {
3379
3570
  const opening = document["opening_message"];
3380
- const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
3381
- const plain = typeof opening === "string" ? opening : Array.isArray(opening) ? opening.map((part) => textOf(part?.["text"])).filter((text) => text !== "").join("\n\n") : "";
3571
+ const parts = Array.isArray(opening) ? partsOf(opening) : void 0;
3572
+ const plain = typeof opening === "string" ? opening : parts === void 0 ? "" : partsText(parts);
3382
3573
  const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
3383
3574
  const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
3384
3575
  const rules = document["rules"];
@@ -3388,7 +3579,7 @@ function infoOf(document, startQuestions = []) {
3388
3579
  tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
3389
3580
  rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
3390
3581
  opening: plain,
3391
- openingParts: parts,
3582
+ ...parts === void 0 ? {} : { openingParts: parts },
3392
3583
  authorName: textOf(author["name"]),
3393
3584
  authorUrl: textOf(author["url"]),
3394
3585
  timeZone: textOf(document["time_zone"]),
@@ -3401,11 +3592,7 @@ function infoOf(document, startQuestions = []) {
3401
3592
  tools: toolsOf(document["tools"]),
3402
3593
  autonomy: document["autonomy"] === true,
3403
3594
  startQuestions,
3404
- alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
3405
- title: textOf(entry["title"]),
3406
- text: entry["text"],
3407
- ...textOf(entry["character"]) === "" ? {} : { character: textOf(entry["character"]) }
3408
- }] : []) : []
3595
+ alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap(alternateOf) : []
3409
3596
  };
3410
3597
  }
3411
3598
  async function readDocument(directory) {
@@ -3443,7 +3630,6 @@ async function changeWorldInfo(directory, edit) {
3443
3630
  if (edit.startQuestions.length === 0) delete document["start_questions"];
3444
3631
  else document["start_questions"] = startQuestionsToFile(edit.startQuestions);
3445
3632
  }
3446
- 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"]);
3447
3633
  if (edit.name !== void 0) document["name"] = edit.name;
3448
3634
  if (edit.description !== void 0) document["description"] = edit.description;
3449
3635
  if (edit.tags !== void 0) document["metadata"] = {
@@ -3454,7 +3640,11 @@ async function changeWorldInfo(directory, edit) {
3454
3640
  if (edit.rules.length === 0) delete document["rules"];
3455
3641
  else document["rules"] = edit.rules;
3456
3642
  }
3457
- if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
3643
+ if (edit.opening !== void 0) setOrRemove(document, "opening_message", edit.opening);
3644
+ if (edit.openingParts !== void 0) {
3645
+ if (edit.openingParts.length === 0) delete document["opening_message"];
3646
+ else document["opening_message"] = edit.openingParts;
3647
+ }
3458
3648
  if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
3459
3649
  const name = edit.authorName ?? before.authorName;
3460
3650
  const url = edit.authorUrl ?? before.authorUrl;
@@ -3480,7 +3670,7 @@ async function changeWorldInfo(directory, edit) {
3480
3670
  if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
3481
3671
  else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
3482
3672
  title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
3483
- text: entry.text,
3673
+ ...entry.parts === void 0 ? { text: entry.text } : { parts: entry.parts },
3484
3674
  ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
3485
3675
  }));
3486
3676
  }
@@ -5239,7 +5429,7 @@ const about = {
5239
5429
  where: "world.json",
5240
5430
  message: "the world has no tags"
5241
5431
  });
5242
- if (text(info.opening) === "" && !info.openingParts) found.push({
5432
+ if (text(info.opening) === "" && info.openingParts === void 0) found.push({
5243
5433
  severity: "info",
5244
5434
  code: "no-opening",
5245
5435
  where: "world.json",
@@ -5878,6 +6068,42 @@ async function forgetJobs(directory) {
5878
6068
  force: true
5879
6069
  });
5880
6070
  }
6071
+ // src/host/import/output-ceiling.ts
6072
+ /** A share of the model's context window, and the least and the fallback when the window is not known: the default of what one helper request may write. */
6073
+ const AUTO_OUTPUT_SHARE = .1;
6074
+ const AUTO_OUTPUT_MIN = 16e3;
6075
+ const AUTO_OUTPUT_UNKNOWN = 32e3;
6076
+ const windows = /* @__PURE__ */ new Map();
6077
+ /** The most one request may write when the setting is automatic (0): a tenth of the window, at least 16 000 tokens. */
6078
+ function autoOutputCeiling(window) {
6079
+ return window === void 0 ? AUTO_OUTPUT_UNKNOWN : Math.max(AUTO_OUTPUT_MIN, Math.round(window * AUTO_OUTPUT_SHARE));
6080
+ }
6081
+ /** The ceiling for requests that cannot wait for the window to be looked up: what was learned from an earlier lookup of the model, or the fallback. */
6082
+ function knownOutputCeiling(configured, model) {
6083
+ if (configured > 0) return configured;
6084
+ return autoOutputCeiling(model === void 0 ? void 0 : windows.get(`${model.provider}/${model.model}`));
6085
+ }
6086
+ /** The most one request of a helper may write: the setting when it names a number, else a share of the context window of the model the helper runs on (the chat's own unless one is named). */
6087
+ async function outputCeiling(configured, agent, named, signal) {
6088
+ if (configured > 0) return configured;
6089
+ const config = agent.session.requestHeader()?.config;
6090
+ const model = named ?? (config?.provider === void 0 || config.model === void 0 ? void 0 : {
6091
+ provider: config.provider,
6092
+ model: config.model
6093
+ });
6094
+ if (model === void 0) return autoOutputCeiling();
6095
+ const key = `${model.provider}/${model.model}`;
6096
+ let window = windows.get(key);
6097
+ if (window === void 0) {
6098
+ try {
6099
+ window = (await agent.ctx.llm.resolveModelInfo(model.provider, model.model, signal)).context?.contextWindow;
6100
+ } catch {
6101
+ window = void 0;
6102
+ }
6103
+ if (window !== void 0) windows.set(key, window);
6104
+ }
6105
+ return autoOutputCeiling(window);
6106
+ }
5881
6107
  // src/host/import/tools.ts
5882
6108
  const residencyOf = (agent) => agent.ctx.get("roleplayOrchestration")?.residency;
5883
6109
  const SURVEY_TOOL = "import_survey";
@@ -6085,53 +6311,64 @@ function importNotice(phase, text) {
6085
6311
  done: phase === "done" ? text("import/notice-done") : ""
6086
6312
  });
6087
6313
  }
6088
- /** Hears the `/import-st` command in an authoring chat, makes that turn an import turn, and does not let it end before the import is done. */
6089
- function importHooks(ctx, worlds, prompting) {
6090
- const textFor = (worldId) => (id, variables) => prompting.prompts().text(id, worldId === void 0 ? void 0 : prompting.languages().get(worldId), {
6091
- ...toolNames,
6092
- ...variables
6093
- });
6094
- const imports = /* @__PURE__ */ new Map();
6095
- const objections = /* @__PURE__ */ new Map();
6096
- const repairs = /* @__PURE__ */ new Map();
6314
+ /** The text of an import's prompts for a world: in the language of its authoring chat, with the names of the import tools filled in. */
6315
+ const importTextFor = (prompting) => (worldId) => (id, variables) => prompting.prompts().text(id, worldId === void 0 ? void 0 : prompting.languages().get(worldId), {
6316
+ ...toolNames,
6317
+ ...variables
6318
+ });
6319
+ /**
6320
+ * The `/import-st` command of an authoring chat, and the gate that does not let an import turn end before the import is done. Running the command makes the next turn of the chat an import turn
6321
+ * (`beginImport`) and gives the chat the procedure of the step the import has reached.
6322
+ */
6323
+ function importHooks(ctx, worlds, prompting, state) {
6324
+ const textFor = importTextFor(prompting);
6325
+ const { importing: imports, objections, repairs } = state;
6097
6326
  const authoring = (agent) => agent.session.header.origin === "subagent" || authoredWorldOf(agent.session.id) === void 0 ? void 0 : agent.session.id;
6098
- ctx.on("agent/pre-step", async (payload, next) => {
6099
- const decision = await next();
6100
- const chat = authoring(payload.agent);
6101
- if (decision.kind !== "enter" || payload.step !== 1 || chat === void 0) return decision;
6102
- const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
6103
- if (parseImportCommand(text) === void 0) return decision;
6104
- const worldId = authoredWorldOf(chat);
6105
- const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
6106
- const phase = record === void 0 ? void 0 : await importPhase(record.directory);
6107
- if (phase !== void 0 && phase !== "done") {
6108
- imports.set(chat, payload.turn);
6109
- objections.delete(chat);
6110
- repairs.delete(chat);
6111
- }
6112
- if (phase === "repair" && record !== void 0) await startRepair(record.directory);
6113
- return {
6114
- ...decision,
6115
- messages: [...decision.messages, createUserMessage({
6327
+ registerCommands(ctx, [{
6328
+ name: IMPORT_COMMAND.slice(1),
6329
+ description: "Import the character card waiting in this world",
6330
+ hint: "<card file> [what to do]",
6331
+ recordInput: false,
6332
+ handler: async ({ agent, rawInput }) => {
6333
+ const chat = authoring(agent);
6334
+ if (chat === void 0) return {
6335
+ kind: "error",
6336
+ text: `${IMPORT_COMMAND} runs in the authoring chat of a world`
6337
+ };
6338
+ const begun = await beginImport({
6339
+ worlds,
6340
+ text: textFor,
6341
+ state
6342
+ }, chat, importRequestOf(rawInput));
6343
+ if (!begun.ok) return {
6344
+ kind: "error",
6345
+ text: begun.reason
6346
+ };
6347
+ agent.followup(createUserMessage({
6116
6348
  content: [{
6117
6349
  type: "text",
6118
- text: importNotice(phase, textFor(worldId))
6350
+ text: begun.message
6119
6351
  }],
6120
6352
  source: { kind: "roleplay" }
6121
- })]
6122
- };
6123
- });
6353
+ }));
6354
+ return {
6355
+ kind: "success",
6356
+ text: "Importing the card…"
6357
+ };
6358
+ }
6359
+ }]);
6124
6360
  ctx.on("session/event", async (session, event) => {
6125
6361
  if (event.type !== "turn/end" || session.header.origin === "subagent") return;
6126
6362
  const worldId = authoredWorldOf(session.id);
6127
6363
  const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
6364
+ imports.delete(session.id);
6128
6365
  if (record === void 0) return;
6129
6366
  await endReview(record.directory);
6130
6367
  await settleDraft(record.directory);
6131
6368
  });
6132
- ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
6369
+ ctx.on("agent/turn-stopping", async ({ agent }) => {
6133
6370
  const chat = authoring(agent);
6134
- if (chat === void 0 || imports.get(chat) !== turn) return;
6371
+ if (chat === void 0 || !imports.has(chat)) return;
6135
6372
  const worldId = authoredWorldOf(chat);
6136
6373
  const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
6137
6374
  const phase = record === void 0 ? void 0 : await importPhase(record.directory);
@@ -6180,6 +6417,41 @@ function importHooks(ctx, worlds, prompting) {
6180
6417
  }));
6181
6418
  });
6182
6419
  }
6420
+ // src/host/import/begin.ts
6421
+ /** What the authoring chats know of the imports they are running: the chats whose turn is an import turn, and how often each was sent back. */
6422
+ var ImportState = class {
6423
+ importing = /* @__PURE__ */ new Set();
6424
+ objections = /* @__PURE__ */ new Map();
6425
+ repairs = /* @__PURE__ */ new Map();
6426
+ };
6427
+ /**
6428
+ * Makes the next turn of a world's authoring chat an import turn and gives what the chat is told to start it: the procedure of the step the import has reached, then what the person asked.
6429
+ * The `/import-st` command and the plugin's own start of an import both begin here.
6430
+ */
6431
+ async function beginImport(deps, chat, request) {
6432
+ const worldId = authoredWorldOf(chat);
6433
+ const record = worldId === void 0 ? void 0 : await deps.worlds.find(worldId);
6434
+ if (record === void 0) return {
6435
+ ok: false,
6436
+ reason: "an import runs in the authoring chat of a world"
6437
+ };
6438
+ const phase = await importPhase(record.directory);
6439
+ if (phase === void 0) return {
6440
+ ok: false,
6441
+ reason: "no card is waiting to be imported in this world"
6442
+ };
6443
+ if (phase !== "done") {
6444
+ deps.state.importing.add(chat);
6445
+ deps.state.objections.delete(chat);
6446
+ deps.state.repairs.delete(chat);
6447
+ }
6448
+ if (phase === "repair") await startRepair(record.directory);
6449
+ const notice = importNotice(phase, deps.text(worldId));
6450
+ return {
6451
+ ok: true,
6452
+ message: request.trim() === "" ? notice : `${notice}\n\n${request.trim()}`
6453
+ };
6454
+ }
6183
6455
  // src/shared/import-selection.ts
6184
6456
  const MAX_PREVIEW_TEXT = 4e3;
6185
6457
  // src/host/tools/authoring-tools.ts
@@ -6221,6 +6493,6 @@ function limitAuthoringAgents(ctx, kindOf) {
6221
6493
  return await next();
6222
6494
  });
6223
6495
  }
6224
- export { readSource as $, editsSince as A, loadCommands as At, addressesToFetch as B, isPng as Bt, worldFieldChanges as C, FACTIONS_DIR as Ct, loadCardEvidence as D, parseDiceFile as Dt, loadWorldParts as E, loadDice as Et, localChanges as F, CHARACTERS_DIR as Ft, vetUrl as G, DICE_RESULTS as Gt, fetchPictures as H, readCard as Ht, readOrigin as I, loadCharacters as It, UPDATE_FOLDER as J, cardCharacter as K, authoredWorldOf as Kt, writeOrigin as L, knownOutputCeiling as Lt, describeChanges as M, CALENDAR_FILE_NAME as Mt, hashWorld as N, loadCalendar as Nt, CHECK_COMMANDS as O, COMMANDS_FILE_NAME as Ot, isUnchanged as P, parseCalendarFile as Pt, entitiesByPiece as Q, CatalogueError as R, ImportCardError as Rt, pictureChange as S, loadItems as St, readWorldInfo as T, DICE_FILE_NAME as Tt, guardedLookup as U, DICE_COMPARISONS as Ut, candidateUrls as V, pictureOf as Vt, mergeReports as W, DICE_READINGS as Wt, cardPieces as X, baseId as Y, cardTools as Z, runChecks as _, TRIGGERS_FILE_NAME as _t, importHooks as a, populateCharacters as at, diffText as b, loadLocations as bt, importPhase as c, populateFactions as ct, markReady as d, populateLocations as dt, checkWorld as et, settleDraft as f, populateLore as ft, CHECKS as g, routineProblems as gt, presentReport as h, populateVariables as ht, contextOf as i, populateCalendar as it, writeSnapshot as j, parseCommandsFile as jt, recordProvenance as k, commandVariable as kt, isReviewing as l, populateItems as lt, checkImported as m, populateTriggers as mt, limitAuthoringAgents as n, withScratchStory as nt, importTools as o, populateClock as ot, structureImport as p, populateRoutines as pt, writePortrait as q, authoringChatSessionId as qt, MAX_PREVIEW_TEXT as r, knowsCharacter as rt, worldOf as s, populateDice as st, AuthoringTools as t, loadValidatedWorld as tt, keepDraft as u, populateKnowledge as ut, addressChanges as v, loadTriggers as vt, editWorldInfo as w, loadFactions as wt, matchPieces as x, ITEMS_DIR as xt, cardChanges as y, LOCATIONS_DIR as yt, addressKey as z, cardFormat as zt };
6496
+ export { checkWorld as $, authoringChatSessionId as $t, loadWorldParts as A, lettersOf$1 as At, localChanges as B, loadCommands as Bt, cardChanges as C, loadDice as Ct, worldFieldChanges as D, parseCalendarFile as Dt, pictureChange as E, loadCalendar as Et, editsSince as F, cardTools as Ft, addressesToFetch as G, cardFormat as Gt, writeOrigin as H, TRIGGERS_FILE_NAME as Ht, writeSnapshot as I, entitiesByPiece as It, guardedLookup as J, readCard as Jt, candidateUrls as K, isPng as Kt, describeChanges as L, readSource as Lt, CHECK_COMMANDS as M, UPDATE_FOLDER as Mt, CHECK_COMMAND_DESCRIPTIONS as N, baseId as Nt, editWorldInfo as O, CHARACTERS_DIR as Ot, recordProvenance as P, cardPieces as Pt, writePortrait as Q, authoredWorldOf as Qt, hashWorld as R, COMMANDS_FILE_NAME as Rt, addressChanges as S, DICE_FILE_NAME as St, matchPieces as T, CALENDAR_FILE_NAME as Tt, CatalogueError as U, loadTriggers as Ut, readOrigin as V, parseCommandsFile as Vt, addressKey as W, ImportCardError as Wt, vetUrl as X, DICE_READINGS as Xt, mergeReports as Y, DICE_COMPARISONS as Yt, cardCharacter as Z, DICE_RESULTS as Zt, structureImport as _, loadLocations as _t, beginImport as a, populateClock as at, CHECKS as b, FACTIONS_DIR as bt, importTextFor as c, populateItems as ct, knownOutputCeiling as d, populateLore as dt, loadValidatedWorld as et, importPhase as f, populateRoutines as ft, settleDraft as g, LOCATIONS_DIR as gt, markReady as h, routineProblems as ht, ImportState as i, populateCharacters as it, loadCardEvidence as j, shapeOpening as jt, readWorldInfo as k, loadCharacters as kt, importTools as l, populateKnowledge as lt, keepDraft as m, populateVariables as mt, limitAuthoringAgents as n, knowsCharacter as nt, contextOf as o, populateDice as ot, isReviewing as p, populateTriggers as pt, fetchPictures as q, pictureOf as qt, MAX_PREVIEW_TEXT as r, populateCalendar as rt, importHooks as s, populateFactions as st, AuthoringTools as t, withScratchStory as tt, worldOf as u, populateLocations as ut, checkImported as v, ITEMS_DIR as vt, diffText as w, parseDiceFile as wt, runChecks as x, loadFactions as xt, presentReport as y, loadItems as yt, isUnchanged as z, commandVariable as zt };
6225
6497
 
6226
- //# sourceMappingURL=authoring-tools-BZr4bgBy.js.map
6498
+ //# sourceMappingURL=authoring-tools-B_qYKK8c.js.map