@dsh-agentic-roleplay/core 0.12.1 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/cordis.patch.yml +108 -0
  2. package/lib/{access-DifaiHrI.js → access-Csp80TFX.js} +2 -2
  3. package/lib/{authoring-tools-VOaXzr_R.js → authoring-tools-hacA5fG-.js} +1910 -1853
  4. package/lib/authoring.js +42 -34
  5. package/lib/{child-DzZ-aI6k.js → child-DTdY14S9.js} +45 -6
  6. package/lib/client.js +830 -571
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +3 -3
  9. package/lib/{dev-context-Bdm-eVer.js → dev-context-Cgv_wZbG.js} +12 -2
  10. package/lib/doctor.js +5 -4
  11. package/lib/{gallery-Ctz-UoFk.js → gallery-BNg0rPTp.js} +3 -3
  12. package/lib/{generator-Cv6WWmZT.js → generator-9-5at9cZ.js} +2 -2
  13. package/lib/helper.js +4 -10
  14. package/lib/{hooks-BdR3mBeM.js → hooks-DlrFO4aQ.js} +216 -45
  15. package/lib/images.js +4 -4
  16. package/lib/index.js +67 -45
  17. package/lib/{jail-Cp4zEfip.js → jail-DVbPSC0R.js} +2 -2
  18. package/lib/{library-BU2A_Dx8.js → library-DTxakw0z.js} +2 -2
  19. package/lib/{lorebook-author-tools-DUKcQu8P.js → lorebook-author-tools-dupq-kb_.js} +6 -6
  20. package/lib/lorebook-authoring.js +7 -6
  21. package/lib/{narration-CDsJ5wxH.js → narration--K2XVIHI.js} +2 -2
  22. package/lib/orchestration.js +12 -12
  23. package/lib/{pack-jail-CzHQu0n3.js → pack-jail-Bq0fzKi4.js} +43 -16
  24. package/lib/{packs-BZ-45J4-.js → packs-D-7EU3yU.js} +2 -2
  25. package/lib/{presenter-agent-C2ZkoxZu.js → presenter-agent-vFOxIuWv.js} +6 -6
  26. package/lib/{preset-BPnRPW-1.js → preset-RHcOG55T.js} +4 -4
  27. package/lib/{preset-author-tools-DBqPwn-o.js → preset-author-tools-Dwxnpv6V.js} +6 -6
  28. package/lib/preset-authoring.js +7 -6
  29. package/lib/{reflection-Cuy0YLv0.js → reflection-DibpEUQK.js} +7 -7
  30. package/lib/{serial-BZNeK57v.js → serial-CDGoXYh-.js} +1317 -1276
  31. package/lib/{turn-guard-xaFxYc1T.js → turn-guard-DDxikrq7.js} +3 -3
  32. package/package.json +4 -3
@@ -1,10 +1,10 @@
1
- import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-DzZ-aI6k.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-BZNeK57v.js";
3
- import { f as parseSwitchboard } from "./narration-CDsJ5wxH.js";
4
- import { n as atomicWrite, r as atomicWriteJson } from "./access-DifaiHrI.js";
5
- import { G as readDocument$1, J as errorMessage, K as Reader, Q as copyWorldPrompts, U as commandFlagKey, V as plotReferenceProblems, X as PROMPTS_FOLDER, _t as COMPARISONS, a as externalGiven, at as shippedText, ct as InvalidWorldError, nt as promptProblem, q as formatIssue, rt as shippedLanguages, s as externalWithheld, t as externalToolLimit, tt as listFiles, z as loadPlots } from "./hooks-BdR3mBeM.js";
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 SLOTS_FILE_NAME, Bt as findPanel, C as ROLE_TABLE, Ct as IMPORT_FOLDER, Dt as openingText, E as askYesNo, Et as PICTURE_FILE, Gt as loadVariables, Ht as dialectOf, Jt as LORE_FILE_NAME, M as WORLD_FILE_NAME, N as parseWorldFile, Qt as ITEM_FILE_NAME, R as startQuestionsToFile, Rt as IMPORT_COMMAND, S as ROLES, St as withPlayer, Vt as splitPanels, Wt as VARIABLES_FILE_NAME, Xt as LOCATION_FILE_NAME, Yt as parseLoreFile, Zt as parseLocationFile, _ as pruneRelationships, _t as loadLore, a as characterDocument, an as parseCharacterFile, b as classifyItems, bt as itemise, c as extractStyle, d as inert, en as parseItemFile, f as loreDocuments, g as pruneMembers, gt as LORE_DIR, h as pruneLoreSubjects, i as asWritten, in as CHARACTER_FILE_NAME, j as yesAt, jt as InvalidEditProblems, k as noAt, kt as readImportFolder, ln as WEEKDAY_NAMES, m as pruneLinks, nn as FACTION_FILE_NAME, o as emptyExtracted, on as guarded, p as pruneKnowledge, qt as variableProblems, r as addLore, rn as parseFactionFile, s as extractEntities, t as SerialQueue, tn as parseSlotsFile, u as extractVariables, un as DEFAULT_SLOTS, v as sourcesFor, vt as subfolders, w as isLeftOut, x as findEntity, y as buildRoster, yt as cleanText, zt as importRequestOf } from "./serial-CDGoXYh-.js";
3
+ import { f as parseSwitchboard } from "./narration--K2XVIHI.js";
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, 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-DlrFO4aQ.js";
6
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-BU2A_Dx8.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";
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,1843 @@ 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;
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
+ ];
1105
+ }
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/repair.ts
1134
+ const ENTITY_FILE = /^(characters|locations|factions|items|lore)\/[^/]+\/(character|location|faction|item|lore)\.json$/;
1135
+ /** Fields a document cannot do without, and fields that tie it to others: never dropped, whatever the problem says. */
1136
+ const KEPT = /* @__PURE__ */ new Set([
1137
+ "id",
1138
+ "name",
1139
+ "role",
1140
+ "kind",
1141
+ "tier",
1142
+ "from",
1143
+ "to",
1144
+ "parent",
1145
+ "summary"
1146
+ ]);
1147
+ const ABOUT_VALUE = /^(must be|is longer than|has more than|is not one of|must not|cannot be)/;
1148
+ const STEP = /([^.[\]]+)|\[(\d+)\]/g;
1149
+ const stepsOf = (field) => [...field.matchAll(STEP)].map((match) => match[2] === void 0 ? match[1] : Number(match[2]));
1150
+ /** Removes what `steps` names; false when it is not there. */
1151
+ function remove(root, steps) {
1152
+ let at = root;
1153
+ for (const step of steps.slice(0, -1)) {
1154
+ at = at?.[step];
1155
+ if (typeof at !== "object" || at === null) return void 0;
1156
+ }
1157
+ const last = steps.at(-1);
1158
+ if (typeof at !== "object" || at === null || !(last in at)) return void 0;
1159
+ const value = at[last];
1160
+ if (Array.isArray(at) && typeof last === "number") at.splice(last, 1);
1161
+ else delete at[last];
1162
+ return { value };
1163
+ }
1539
1164
  /**
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.
1165
+ * 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
1166
+ * 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.
1542
1167
  */
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"));
1547
- }
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
- }]
1600
- });
1168
+ async function repairFields(directory, problems) {
1169
+ const repairs = [];
1170
+ const byFile = /* @__PURE__ */ new Map();
1171
+ for (const problem of problems) {
1172
+ if (!ENTITY_FILE.test(problem.where)) continue;
1173
+ const split = problem.message.indexOf(": ");
1174
+ if (split < 0) continue;
1175
+ const field = problem.message.slice(0, split);
1176
+ const because = problem.message.slice(split + 2);
1177
+ if (!/^[\w.[\]]+$/.test(field) || !ABOUT_VALUE.test(because) || KEPT.has(stepsOf(field)[0])) continue;
1178
+ byFile.set(problem.where, [...byFile.get(problem.where) ?? [], {
1179
+ field,
1180
+ because
1181
+ }]);
1601
1182
  }
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
- };
1183
+ for (const [file, fields] of byFile) {
1184
+ const document = JSON.parse(await readFile(join(directory, file), "utf8"));
1185
+ for (const { field, because } of fields.sort((a, b) => b.field.localeCompare(a.field, void 0, { numeric: true }))) {
1186
+ const dropped = remove(document, stepsOf(field));
1187
+ if (dropped !== void 0) repairs.push({
1188
+ file,
1189
+ field,
1190
+ value: dropped.value,
1191
+ because
1192
+ });
1193
+ }
1194
+ if (repairs.some((repair) => repair.file === file)) await atomicWrite(join(directory, file), `${JSON.stringify(document, null, 2)}\n`);
1610
1195
  }
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
- };
1196
+ return repairs;
1617
1197
  }
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");
1626
- try {
1627
- 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);
1639
- } catch (error) {
1640
- return {
1641
- commands: [],
1642
- triggers: [],
1643
- notes: [`the casting guidance was not turned into commands and triggers: ${error instanceof Error ? error.message : String(error)}`]
1644
- };
1645
- }
1198
+ // src/host/worlds/world-file-io.ts
1199
+ const queue = new SerialQueue();
1200
+ /**
1201
+ * 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
1202
+ * back; run side by side, the last one to write would take back what the others changed.
1203
+ */
1204
+ function serialized(directory, work) {
1205
+ return queue.run(directory, work);
1646
1206
  }
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);
1207
+ /** 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. */
1208
+ function updateWorldFile(directory, update) {
1209
+ return serialized(directory, async () => {
1210
+ const file = join(directory, WORLD_FILE_NAME);
1211
+ const text = await readFile(file, "utf8");
1212
+ const document = JSON.parse(text.replace(/^/, ""));
1213
+ await update(document);
1214
+ await atomicWrite(file, JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") || text.trim() === "" ? "\n" : ""));
1215
+ return document;
1216
+ });
1664
1217
  }
1218
+ // src/host/characters/load.ts
1219
+ const CHARACTERS_DIR = "characters";
1665
1220
  /**
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.
1221
+ * Read the cast of one world: every subfolder of `<world>/characters/` that
1222
+ * holds a `character.json`. Ids must be unique; a repeated one is reported and
1223
+ * the later character skipped.
1668
1224
  */
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)
1710
- }
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"))
1722
- });
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
1225
+ async function loadCharacters(worldDir) {
1226
+ const dir = join(worldDir, CHARACTERS_DIR);
1227
+ const result = {
1228
+ characters: [],
1229
+ problems: []
1728
1230
  };
1231
+ let folders;
1232
+ try {
1233
+ folders = await subfolders(dir);
1234
+ } catch (error) {
1235
+ result.problems.push({
1236
+ path: dir,
1237
+ message: errorMessage(error)
1238
+ });
1239
+ return result;
1240
+ }
1241
+ const folderById = /* @__PURE__ */ new Map();
1242
+ for (const folder of folders) {
1243
+ const file = join(dir, folder, CHARACTER_FILE_NAME);
1244
+ try {
1245
+ const character = await readDocument$1(file, (text) => parseCharacterFile(text, folder), result.problems);
1246
+ if (character === void 0) continue;
1247
+ const owner = folderById.get(character.id);
1248
+ if (owner !== void 0) {
1249
+ result.problems.push({
1250
+ path: file,
1251
+ message: `id "${character.id}" is already used by ${owner}`
1252
+ });
1253
+ continue;
1254
+ }
1255
+ folderById.set(character.id, folder);
1256
+ result.characters.push(character);
1257
+ } catch (error) {
1258
+ if (error.code !== "ENOENT") result.problems.push({
1259
+ path: file,
1260
+ message: errorMessage(error)
1261
+ });
1262
+ }
1263
+ }
1264
+ return result;
1729
1265
  }
1730
- // src/host/import/outcomes.ts
1266
+ // src/host/calendar/load.ts
1267
+ const CALENDAR_FILE_NAME = "calendar.json";
1268
+ const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
1731
1269
  /**
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.
1270
+ * 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`,
1271
+ * `09-21..09-22`, `nth:mon:1`, `season:winter`, a month, a weekday); it cannot name another holiday.
1734
1272
  */
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"
1273
+ function parseCalendarFile(text) {
1274
+ const issues = [];
1275
+ const reader = Reader.fromJson(text, issues);
1276
+ if (reader === void 0) return {
1277
+ ok: false,
1278
+ issues
1774
1279
  };
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"
1280
+ const hemisphere = reader.oneOf("hemisphere", ["north", "south"], "north");
1281
+ const seen = /* @__PURE__ */ new Set();
1282
+ const holidays = reader.objects("holidays").flatMap((entry) => {
1283
+ const id = entry.string("id", { required: true });
1284
+ const name = entry.string("name", { required: true });
1285
+ const on = entry.strings("on");
1286
+ if (id !== void 0 && !HOLIDAY_ID.test(id)) entry.fail("id", "is made of letters, digits, \"-\" and \"_\" (at most 60)");
1287
+ if (id !== void 0 && seen.has(id)) entry.fail("id", `"${id}" is used by another holiday`);
1288
+ if (id !== void 0) seen.add(id);
1289
+ 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(", ")}`);
1290
+ for (const problem of dayTokenProblems(on, "on")) entry.fail("on", problem.replace(/^on: /, ""));
1291
+ return id === void 0 || name === void 0 ? [] : [{
1292
+ id,
1293
+ name,
1294
+ on
1295
+ }];
1296
+ });
1297
+ if (holidays.length > 60) reader.fail("holidays", `a world has at most 60 holidays`);
1298
+ return issues.length > 0 ? {
1299
+ ok: false,
1300
+ issues
1301
+ } : {
1302
+ ok: true,
1303
+ value: {
1304
+ hemisphere,
1305
+ holidays
1306
+ }
1778
1307
  };
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"
1308
+ }
1309
+ /** The calendar of a world: an optional `<world>/calendar.json`; a world without one has none. */
1310
+ async function loadCalendar(worldDir) {
1311
+ const result = {
1312
+ calendar: {
1313
+ hemisphere: "north",
1314
+ holidays: []
1315
+ },
1316
+ problems: []
1784
1317
  };
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
- };
1318
+ const file = join(worldDir, CALENDAR_FILE_NAME);
1319
+ try {
1320
+ result.calendar = await readDocument$1(file, parseCalendarFile, result.problems) ?? result.calendar;
1321
+ } catch (error) {
1322
+ if (error.code !== "ENOENT") result.problems.push({
1323
+ path: file,
1324
+ message: errorMessage(error)
1325
+ });
1797
1326
  }
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"
1327
+ return result;
1328
+ }
1329
+ // src/host/dice/load.ts
1330
+ const DICE_FILE_NAME = "dice.json";
1331
+ function readBand(band) {
1332
+ const label = band.string("label", { required: true });
1333
+ const result = band.oneOf("result", DICE_RESULTS, "failed");
1334
+ const min = band.number("min");
1335
+ const max = band.number("max");
1336
+ const critical = band.raw("critical");
1337
+ if (critical !== void 0 && critical !== null && typeof critical !== "boolean") band.fail("critical", "must be true or false");
1338
+ if (band.raw("result") === void 0) band.fail("result", `is required: one of ${DICE_RESULTS.join(", ")}`);
1339
+ return label === void 0 ? void 0 : {
1340
+ label,
1341
+ result,
1342
+ ...min === void 0 ? {} : { min },
1343
+ ...max === void 0 ? {} : { max },
1344
+ ...critical === true ? { critical: true } : {}
1805
1345
  };
1806
1346
  }
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]
1347
+ /**
1348
+ * 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:
1349
+ * the game master rolls a check and is told the band the roll fell in, never a number to interpret.
1350
+ */
1351
+ function parseDiceFile(text) {
1352
+ const issues = [];
1353
+ const reader = Reader.fromJson(text, issues);
1354
+ if (reader === void 0) return {
1355
+ ok: false,
1356
+ issues
1357
+ };
1358
+ const checks = reader.objects("checks").flatMap((entry) => {
1359
+ const key = entry.string("key", { required: true });
1360
+ const name = entry.string("name", { required: true });
1361
+ const use = entry.string("use", { required: true });
1362
+ const dice = entry.string("dice", { required: true });
1363
+ const reading = entry.oneOf("reading", DICE_READINGS, "total");
1364
+ const compare = entry.oneOf("compare", DICE_COMPARISONS, "absolute");
1365
+ const hit = entry.number("hit", { min: 1 });
1366
+ const modifier = entry.string("modifier");
1367
+ const bands = entry.objects("bands").flatMap((band) => {
1368
+ const read = readBand(band);
1369
+ return read === void 0 ? [] : [read];
1370
+ });
1371
+ if (key === void 0 || name === void 0 || use === void 0 || dice === void 0) return [];
1372
+ const definition = {
1373
+ key,
1374
+ name,
1375
+ use,
1376
+ dice,
1377
+ reading,
1378
+ compare,
1379
+ bands,
1380
+ ...hit === void 0 ? {} : { hit },
1381
+ ...modifier === void 0 || modifier === "" ? {} : { modifier }
1818
1382
  };
1383
+ for (const problem of checkProblems(definition)) entry.fail("", problem);
1384
+ return [definition];
1819
1385
  });
1386
+ const seen = /* @__PURE__ */ new Set();
1387
+ for (const check of checks) {
1388
+ if (seen.has(check.key)) reader.fail("checks", `the key "${check.key}" is used by more than one check`);
1389
+ seen.add(check.key);
1390
+ }
1391
+ if (checks.length > 40) reader.fail("checks", `a world has at most 40 checks`);
1392
+ return issues.length > 0 ? {
1393
+ ok: false,
1394
+ issues
1395
+ } : {
1396
+ ok: true,
1397
+ value: checks
1398
+ };
1820
1399
  }
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) {
1400
+ /** The checks of a world: an optional `<world>/dice.json`; a world without one has none, and its game master rolls plain dice only. */
1401
+ async function loadDice(worldDir) {
1402
+ const result = {
1403
+ checks: [],
1404
+ problems: []
1405
+ };
1406
+ const file = join(worldDir, DICE_FILE_NAME);
1864
1407
  try {
1865
- return JSON.parse(await readFile(file, "utf8"));
1408
+ result.checks = await readDocument$1(file, parseDiceFile, result.problems) ?? [];
1866
1409
  } catch (error) {
1867
- if (error.code === "ENOENT") return void 0;
1868
- throw error;
1410
+ if (error.code !== "ENOENT") result.problems.push({
1411
+ path: file,
1412
+ message: errorMessage(error)
1413
+ });
1869
1414
  }
1415
+ return result;
1870
1416
  }
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;
1417
+ // src/host/factions/load.ts
1418
+ const FACTIONS_DIR = "factions";
1419
+ async function loadFactions(worldDir) {
1420
+ const dir = join(worldDir, FACTIONS_DIR);
1421
+ const result = {
1422
+ factions: [],
1423
+ problems: []
1424
+ };
1425
+ let folders;
1875
1426
  try {
1876
- read = await readImportFolder(version === "new" ? join(folder, UPDATE_FOLDER) : folder);
1427
+ folders = await subfolders(dir);
1877
1428
  } 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;
1429
+ if (error.code !== "ENOENT") result.problems.push({
1430
+ path: dir,
1431
+ message: errorMessage(error)
1432
+ });
1433
+ return result;
1880
1434
  }
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;
1435
+ const owners = /* @__PURE__ */ new Map();
1436
+ for (const folder of folders) {
1437
+ const file = join(dir, folder, FACTION_FILE_NAME);
1438
+ try {
1439
+ const faction = await readDocument$1(file, (text) => parseFactionFile(text, folder), result.problems);
1440
+ if (faction === void 0) continue;
1441
+ const owner = owners.get(faction.id);
1442
+ if (owner !== void 0) {
1443
+ result.problems.push({
1444
+ path: file,
1445
+ message: `id "${faction.id}" is already used by ${owner}`
1446
+ });
1447
+ continue;
1448
+ }
1449
+ owners.set(faction.id, folder);
1450
+ result.factions.push(faction);
1451
+ } catch (error) {
1452
+ if (error.code !== "ENOENT") result.problems.push({
1453
+ path: file,
1454
+ message: errorMessage(error)
1455
+ });
1912
1456
  }
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
- }));
1457
+ }
1458
+ if (result.factions.length > 100) result.problems.push({
1459
+ path: dir,
1460
+ message: `a world has at most 100 factions`
1461
+ });
1462
+ return result;
1964
1463
  }
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
- };
1464
+ // src/host/items/load.ts
1465
+ const ITEMS_DIR = "items";
1466
+ /** At most this many items in one world. */
1467
+ const MAX_ITEMS = 2e3;
1984
1468
  /**
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.
1987
- */
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."
1469
+ * Read the things of one world: every subfolder of `<world>/items/` that holds an `item.json`, and an
1470
+ * optional `<world>/items/slots.json`. A world with no such folder has none. Ids must be unique; what
1471
+ * a thing is worn in must be a slot, and where it starts, who owns it, what opens it and what it is
1472
+ * inside must exist in the world, with no thing inside itself.
1473
+ */
1474
+ async function loadItems(worldDir, context) {
1475
+ const dir = join(worldDir, ITEMS_DIR);
1476
+ const result = {
1477
+ items: [],
1478
+ slots: DEFAULT_SLOTS.map((slot) => ({ ...slot })),
1479
+ problems: []
1480
+ };
1481
+ let folders;
1482
+ try {
1483
+ folders = await subfolders(dir);
1484
+ } catch (error) {
1485
+ if (error.code !== "ENOENT") result.problems.push({
1486
+ path: dir,
1487
+ message: errorMessage(error)
1488
+ });
1489
+ return result;
1490
+ }
1491
+ try {
1492
+ const own = await readDocument$1(join(dir, SLOTS_FILE_NAME), parseSlotsFile, result.problems);
1493
+ for (const slot of own ?? []) {
1494
+ const at = result.slots.findIndex((existing) => existing.id === slot.id);
1495
+ if (at < 0) result.slots.push(slot);
1496
+ else result.slots[at] = slot;
1497
+ }
1498
+ } catch (error) {
1499
+ if (error.code !== "ENOENT") result.problems.push({
1500
+ path: join(dir, SLOTS_FILE_NAME),
1501
+ message: errorMessage(error)
1502
+ });
1503
+ }
1504
+ const folderOf = /* @__PURE__ */ new Map();
1505
+ for (const folder of folders) {
1506
+ const file = join(dir, folder, ITEM_FILE_NAME);
1507
+ try {
1508
+ const item = await readDocument$1(file, (text) => parseItemFile(text, folder), result.problems);
1509
+ if (item === void 0) continue;
1510
+ const owner = folderOf.get(item.id);
1511
+ if (owner !== void 0) {
1512
+ result.problems.push({
1513
+ path: file,
1514
+ message: `id "${item.id}" is already used by ${owner}`
2064
1515
  });
1516
+ continue;
2065
1517
  }
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}).`
1518
+ folderOf.set(item.id, folder);
1519
+ result.items.push(item);
1520
+ } catch (error) {
1521
+ if (error.code !== "ENOENT") result.problems.push({
1522
+ path: file,
1523
+ message: errorMessage(error)
1524
+ });
1525
+ }
1526
+ }
1527
+ if (result.items.length > 2e3) result.problems.push({
1528
+ path: dir,
1529
+ message: `a world has at most ${MAX_ITEMS} items`
1530
+ });
1531
+ const byId = new Map(result.items.map((item) => [item.id, item]));
1532
+ const slotIds = new Set(result.slots.map((slot) => slot.id));
1533
+ const places = new Map(context.locations.map((location) => [location.id, location]));
1534
+ const characters = new Set(context.characters);
1535
+ const fileOf = (id) => join(dir, folderOf.get(id) ?? id, ITEM_FILE_NAME);
1536
+ for (const item of result.items) {
1537
+ const problem = (message) => {
1538
+ result.problems.push({
1539
+ path: fileOf(item.id),
1540
+ message
1541
+ });
1542
+ };
1543
+ 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})`);
1544
+ if (item.owner !== void 0 && !characters.has(item.owner)) problem(`owner: "${item.owner}" is not a character of this world`);
1545
+ for (const key of item.container?.openedBy ?? []) if (!byId.has(key)) problem(`container.opened_by: "${key}" is not an item of this world`);
1546
+ const { start } = item;
1547
+ if (start.kind === "location") {
1548
+ const place = places.get(start.location);
1549
+ if (place === void 0) problem(`location: "${start.location}" is not a place of this world`);
1550
+ else if (start.feature !== void 0 && !place.features.some((feature) => feature.key === start.feature)) problem(`feature: ${place.name} has no feature "${start.feature}"`);
1551
+ } else if (start.kind === "held" || start.kind === "worn") {
1552
+ if (!characters.has(start.character)) problem(`${start.kind === "held" ? "held_by" : "worn_by"}: "${start.character}" is not a character of this world`);
1553
+ } else if (start.kind === "inside") {
1554
+ const box = byId.get(start.item);
1555
+ if (box === void 0) problem(`inside: "${start.item}" is not an item of this world`);
1556
+ else if (box.container === void 0) problem(`inside: ${box.name} is not a container`);
1557
+ const seen = /* @__PURE__ */ new Set([item.id]);
1558
+ for (let up = box; up !== void 0; up = up.start.kind === "inside" ? byId.get(up.start.item) : void 0) {
1559
+ if (seen.has(up.id)) {
1560
+ problem("inside: the items are inside each other in a circle");
1561
+ break;
2080
1562
  }
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
- });
1563
+ seen.add(up.id);
2099
1564
  }
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)
1565
+ }
1566
+ }
1567
+ for (const place of context.locations) place.exits.forEach((exit, index) => {
1568
+ for (const key of exit.openedBy ?? []) if (!byId.has(key)) result.problems.push({
1569
+ path: join(worldDir, "locations", place.id, "location.json"),
1570
+ message: `exits[${index}].opened_by: "${key}" is not an item of this world`
1571
+ });
1572
+ });
1573
+ return result;
1574
+ }
1575
+ /** The items in an order where each comes after the container it starts in. */
1576
+ function containersFirst(items) {
1577
+ const ordered = [];
1578
+ const placed = /* @__PURE__ */ new Set();
1579
+ const byId = new Map(items.map((item) => [item.id, item]));
1580
+ const place = (item) => {
1581
+ if (placed.has(item.id)) return;
1582
+ placed.add(item.id);
1583
+ const box = item.start.kind === "inside" ? byId.get(item.start.item) : void 0;
1584
+ if (box !== void 0) place(box);
1585
+ ordered.push(item);
1586
+ };
1587
+ for (const item of items) place(item);
1588
+ return ordered;
1589
+ }
1590
+ // src/host/locations/load.ts
1591
+ const LOCATIONS_DIR = "locations";
1592
+ /**
1593
+ * Read the places of one world: every subfolder of `<world>/locations/` that holds a
1594
+ * `location.json`. A world with no such folder has no places, which is fine. Ids must be unique;
1595
+ * every parent and every exit must lead to a place of the world, and the places must not contain
1596
+ * each other in a circle. Every problem is reported with the file it is in.
1597
+ */
1598
+ async function loadLocations(worldDir) {
1599
+ const dir = join(worldDir, LOCATIONS_DIR);
1600
+ const result = {
1601
+ locations: [],
1602
+ problems: []
1603
+ };
1604
+ let folders;
1605
+ try {
1606
+ folders = await subfolders(dir);
1607
+ } catch (error) {
1608
+ if (error.code !== "ENOENT") result.problems.push({
1609
+ path: dir,
1610
+ message: errorMessage(error)
1611
+ });
1612
+ return result;
1613
+ }
1614
+ const files = /* @__PURE__ */ new Map();
1615
+ for (const folder of folders) {
1616
+ const file = join(dir, folder, LOCATION_FILE_NAME);
1617
+ try {
1618
+ const location = await readDocument$1(file, (text) => parseLocationFile(text, folder), result.problems);
1619
+ if (location === void 0) continue;
1620
+ const owner = files.get(location.id);
1621
+ if (owner !== void 0) {
1622
+ result.problems.push({
1623
+ path: file,
1624
+ message: `id "${location.id}" is already used by ${owner}`
2132
1625
  });
1626
+ continue;
2133
1627
  }
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
- }))
1628
+ files.set(location.id, folder);
1629
+ result.locations.push(location);
1630
+ } catch (error) {
1631
+ if (error.code !== "ENOENT") result.problems.push({
1632
+ path: file,
1633
+ message: errorMessage(error)
1634
+ });
1635
+ }
1636
+ }
1637
+ if (result.locations.length > 500) result.problems.push({
1638
+ path: dir,
1639
+ message: `a world has at most 500 places`
1640
+ });
1641
+ const byId = new Map(result.locations.map((location) => [location.id, location]));
1642
+ const fileOf = (id) => join(dir, files.get(id) ?? id, LOCATION_FILE_NAME);
1643
+ for (const location of result.locations) {
1644
+ if (location.parent !== void 0 && !byId.has(location.parent)) result.problems.push({
1645
+ path: fileOf(location.id),
1646
+ message: `parent: "${location.parent}" is not a place of this world`
1647
+ });
1648
+ if (location.parent === location.id) result.problems.push({
1649
+ path: fileOf(location.id),
1650
+ message: "parent: a place cannot be in itself"
1651
+ });
1652
+ location.exits.forEach((exit, index) => {
1653
+ if (!byId.has(exit.to)) result.problems.push({
1654
+ path: fileOf(location.id),
1655
+ message: `exits[${index}].to: "${exit.to}" is not a place of this world`
1656
+ });
1657
+ if (exit.to === location.id) result.problems.push({
1658
+ path: fileOf(location.id),
1659
+ message: `exits[${index}].to: an exit must lead to another place`
1660
+ });
1661
+ });
1662
+ const seen = /* @__PURE__ */ new Set();
1663
+ for (let up = location.parent === location.id ? void 0 : location.parent; up !== void 0 && byId.has(up); up = byId.get(up)?.parent) {
1664
+ if (up === location.id || seen.has(up)) {
1665
+ result.problems.push({
1666
+ path: fileOf(location.id),
1667
+ message: "parent: the places contain each other in a circle"
2169
1668
  });
1669
+ break;
2170
1670
  }
2171
- })
2172
- ];
1671
+ seen.add(up);
1672
+ }
1673
+ }
1674
+ return result;
2173
1675
  }
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;
1676
+ /** The places in an order where each comes after the one it is in. */
1677
+ function parentsFirst(locations) {
1678
+ const ordered = [];
1679
+ const placed = /* @__PURE__ */ new Set();
1680
+ const byId = new Map(locations.map((location) => [location.id, location]));
1681
+ const place = (location) => {
1682
+ if (placed.has(location.id)) return;
1683
+ placed.add(location.id);
1684
+ const parent = location.parent === void 0 ? void 0 : byId.get(location.parent);
1685
+ if (parent !== void 0) place(parent);
1686
+ ordered.push(location);
1687
+ };
1688
+ for (const location of locations) place(location);
1689
+ return ordered;
1690
+ }
1691
+ // src/host/sessions/populate.ts
1692
+ /** What is wrong with how the characters stand towards each other, found before anything is created. */
1693
+ function relationshipProblems(characters) {
1694
+ const ids = new Set(characters.map((character) => character.id));
1695
+ return characters.flatMap((character) => (character.relationships ?? []).flatMap((relation) => {
1696
+ if (relation.to === character.id) return [`${character.id}: relationships: a character has no relationship with itself`];
1697
+ return ids.has(relation.to) ? [] : [`${character.id}: relationships: "${relation.to}" is not a character of this world`];
1698
+ }));
1699
+ }
1700
+ function factionProblems(factions, characters) {
1701
+ const factionIds = new Set(factions.map((faction) => faction.id));
1702
+ const characterIds = new Set(characters.map((character) => character.id));
1703
+ 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) => {
1704
+ if (relation.to.kind === "faction" && relation.to.id === faction.id) return [`${faction.id}: relationships: a faction has no relationship with itself`];
1705
+ 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`];
1706
+ })]);
1707
+ }
1708
+ /** What is wrong with the places, things and directed ways characters are authored to know. */
1709
+ function knowledgeProblems(characters, locations, items, lore = []) {
1710
+ const places = new Map(locations.map((location) => [location.id, location]));
1711
+ const things = new Set(items.map((item) => item.id));
1712
+ const loreIds = new Set(lore.map((entry) => entry.id));
1713
+ 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;
1714
+ return characters.flatMap((character) => {
1715
+ const prefix = `${character.id}: knowledge`;
1716
+ const knowledge = character.knowledge;
1717
+ if (knowledge === void 0) return [];
1718
+ return [
1719
+ ...knowledge.locations.flatMap((key) => places.has(key) ? [] : [`${prefix}.locations: "${key}" is not a place of this world`]),
1720
+ ...knowledge.items.flatMap((key) => things.has(key) ? [] : [`${prefix}.items: "${key}" is not an item of this world`]),
1721
+ ...knowledge.exits.flatMap(({ from, to }) => wayExists(from, to) ? [] : [`${prefix}.exits: there is no exit from "${from}" to "${to}"`]),
1722
+ ...(knowledge.lore ?? []).flatMap((key) => loreIds.has(key) ? [] : [`${prefix}.lore: "${key}" is not lore of this world`])
1723
+ ];
1724
+ });
1725
+ }
1726
+ /** Whether a world's characters include the one a lore entry names by id, name or alias. */
1727
+ function knowsCharacter(characters, reference) {
1728
+ const key = reference.normalize("NFKC").toLowerCase();
1729
+ return characters.some((character) => character.id === reference || [character.name, ...character.aliases].some((name) => name.normalize("NFKC").toLowerCase() === key));
1730
+ }
1731
+ function loreProblems(lore, world) {
1732
+ const ids = {
1733
+ character: new Set(world.characters.map((x) => x.id)),
1734
+ faction: new Set(world.factions.map((x) => x.id)),
1735
+ location: new Set(world.locations.map((x) => x.id)),
1736
+ item: new Set(world.items.map((x) => x.id)),
1737
+ lore: new Set(lore.map((x) => x.id))
1738
+ };
1739
+ return lore.flatMap((entry) => [
1740
+ ...entry.subjects.flatMap((subject) => ids[subject.kind].has(subject.id) ? [] : [`${entry.id}: subjects: "${subject.id}" is not a ${subject.kind} of this world`]),
1741
+ ...entry.knownBy.flatMap((reference) => knowsCharacter(world.characters, reference) ? [] : [`${entry.id}: known_by: "${reference}" is not a character of this world`]),
1742
+ ...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`])
1743
+ ]);
1744
+ }
1745
+ /** `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. */
1746
+ function populateLore(session, definitions, turn = 0) {
1747
+ for (const entry of definitions) session.lore.add({
1748
+ sourceId: entry.id,
1749
+ title: entry.title,
1750
+ kind: entry.kind,
1751
+ scope: entry.scope,
1752
+ summary: entry.summary,
1753
+ body: entry.body,
1754
+ ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
1755
+ ...entry.endsAt === void 0 ? {} : { endsAt: entry.endsAt },
1756
+ subjects: [],
1757
+ related: [],
1758
+ sources: entry.sources
1759
+ });
1760
+ const subject = (wanted) => ({
1761
+ kind: wanted.kind,
1762
+ 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
1763
+ });
1764
+ for (const entry of definitions) session.lore.update(session.lore.getBySourceId(entry.id).id, {
1765
+ subjects: entry.subjects.map(subject),
1766
+ related: entry.related.map((id) => session.lore.getBySourceId(id).id)
1767
+ });
1768
+ for (const entry of definitions) {
1769
+ const lore = session.lore.getBySourceId(entry.id);
1770
+ for (const reference of entry.knownBy) {
1771
+ const knower = session.characters.getBySourceId(reference) ?? session.characters.findByName(reference)[0];
1772
+ if (knower !== void 0) session.knowledge.learn(knower.id, "lore", lore.id, turn);
1773
+ }
1774
+ }
1775
+ }
1776
+ /** What is wrong with where the characters start, found before anything is created. */
1777
+ function startingPlaceProblems(characters, locations) {
1778
+ const byId = new Map(locations.map((location) => [location.id, location]));
1779
+ return characters.flatMap((character) => {
1780
+ const place = character.start.place;
1781
+ if (place === void 0) return [];
1782
+ const location = byId.get(place.location);
1783
+ if (location === void 0) return [`${character.id}: start.location "${place.location}" is not a place of this world`];
1784
+ 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"})`];
1785
+ return [];
1786
+ });
1787
+ }
1788
+ /** Declare what the world tracks and give everything the values it starts with. */
1789
+ function populateVariables(session, defs, world) {
1790
+ for (const def of defs) session.variables.define(def);
1791
+ const give = (kind, id, values) => {
1792
+ for (const [key, value] of Object.entries(values ?? {})) session.variables.set(key, kind, id, { value }, 0);
1793
+ };
1794
+ for (const entry of world.characters) give("character", session.characters.getBySourceId(entry.id).id, entry.variables);
1795
+ for (const entry of world.items) give("item", session.items.getBySourceId(entry.id).id, entry.variables);
1796
+ for (const entry of world.locations) give("location", session.locations.getBySourceId(entry.id).id, entry.variables);
1797
+ give("world", 0, world.values);
1798
+ }
1799
+ /** What is wrong with the days characters are given, found before anything is created: places that are not in the world. */
1800
+ function routineProblems(characters, locations, calendar) {
1801
+ calendar ??= {
1802
+ hemisphere: "north",
1803
+ holidays: []
1804
+ };
1805
+ const byId = new Map(locations.map((location) => [location.id, location]));
1806
+ const holidays = new Set(calendar.holidays.map((holiday) => holiday.id));
1807
+ return characters.flatMap((character) => (character.routine ?? []).flatMap((window, index) => {
1808
+ const days = dayTokenProblems(window.on ?? [], `${character.id}: routine[${index}].on`, holidays);
1809
+ if (days.length > 0) return days;
1810
+ if (window.location === void 0) return [];
1811
+ const location = byId.get(window.location);
1812
+ if (location === void 0) return [`${character.id}: routine[${index}].location "${window.location}" is not a place of this world`];
1813
+ 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}`];
1814
+ return [];
1815
+ }));
1816
+ }
1817
+ /** Keeps the checks of the world with the story: what its game master rolls and how the dice are read. */
1818
+ function populateDice(session, checks) {
1819
+ for (const check of checks) session.dice.define(check);
1820
+ }
1821
+ /** Keeps the world's calendar with the story, for the days a routine or a trigger waits for. */
1822
+ function populateCalendar(session, calendar) {
1823
+ if (calendar.holidays.length > 0 || calendar.hemisphere !== "north") writeCalendar(session.metadata, calendar);
1824
+ }
1825
+ /** Gives each character its recurring day, with the places by their ids in the world. */
1826
+ function populateRoutines(session, characters) {
1827
+ for (const { id, routine } of characters) {
1828
+ if (routine === void 0 || routine.length === 0) continue;
1829
+ session.routines.replace(session.characters.getBySourceId(id).id, routine.map((window) => ({
1830
+ days: window.days.map((day) => WEEKDAY_NAMES.indexOf(day)),
1831
+ on: window.on ?? [],
1832
+ start: parseTimeOfDay(window.from),
1833
+ end: parseTimeOfDay(window.to),
1834
+ activity: window.activity,
1835
+ interruptible: window.interruptible,
1836
+ ...window.sleep === true ? { sleep: true } : {},
1837
+ ...window.location === void 0 ? {} : { locationId: session.locations.getBySourceId(window.location).id },
1838
+ ...window.feature === void 0 ? {} : { featureKey: window.feature },
1839
+ ...window.position === void 0 ? {} : { position: window.position }
1840
+ })));
1841
+ }
1842
+ }
1843
+ /** 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). */
1844
+ function populateLocations(session, locations) {
1845
+ const ordered = parentsFirst(locations);
1846
+ for (const { id, name, description, parent, features, visualIdentity } of ordered) {
1847
+ const parentId = parent === void 0 ? void 0 : session.locations.getBySourceId(parent)?.id;
1848
+ const stored = session.locations.add({
1849
+ sourceId: id,
1850
+ name,
1851
+ description,
1852
+ features,
1853
+ ...parentId === void 0 ? {} : { parentId }
1854
+ });
1855
+ if (visualIdentity !== void 0) session.visualIdentities.set("location", stored.id, visualIdentity);
1856
+ }
1857
+ for (const location of ordered) {
1858
+ const from = session.locations.getBySourceId(location.id);
1859
+ for (const exit of location.exits) {
1860
+ const to = session.locations.getBySourceId(exit.to);
1861
+ const shared = {
1862
+ ...exit.travelSeconds === void 0 ? {} : { travelSeconds: exit.travelSeconds },
1863
+ state: exit.state,
1864
+ note: exit.note
1865
+ };
1866
+ if (session.locations.getExit(from.id, to.id) === void 0) session.locations.addExit({
1867
+ fromId: from.id,
1868
+ toId: to.id,
1869
+ description: exit.description,
1870
+ ...shared
1871
+ });
1872
+ if (!exit.oneWay && session.locations.getExit(to.id, from.id) === void 0) session.locations.addExit({
1873
+ fromId: to.id,
1874
+ toId: from.id,
1875
+ description: exit.backDescription ?? exit.description,
1876
+ ...shared
1877
+ });
1878
+ }
1879
+ }
1880
+ }
1881
+ /**
1882
+ * Put a world's cast into a new session: each character with the state it
1883
+ * starts in and its intents. The player controls the character whose world id
1884
+ * is `playerId`; the agent controls everyone else.
1885
+ */
1886
+ function populateCharacters(session, characters, playerId) {
1887
+ for (const { id, start, relationships: _relationships, knowledge: _knowledge, routine: _routine, visualIdentity, ...identity } of characters) {
1888
+ const character = session.characters.add({
1889
+ ...identity,
1890
+ sourceId: id,
1891
+ control: id === playerId ? "player" : "agent"
1892
+ });
1893
+ if (visualIdentity !== void 0) session.visualIdentities.set("character", character.id, visualIdentity);
1894
+ const { intents, place, emotion, ...state } = start;
1895
+ session.characterStates.create(character.id, state);
1896
+ if (emotion !== void 0) for (const axis of [
1897
+ "valence",
1898
+ "arousal",
1899
+ "dominance"
1900
+ ]) session.variables.set(axis, "character", character.id, {
1901
+ value: emotion.immediate[axis],
1902
+ baseline: emotion.baseline[axis]
1903
+ }, 0);
1904
+ for (const intent of intents) session.intents.add(character.id, intent);
1905
+ if (place !== void 0) {
1906
+ const location = session.locations.getBySourceId(place.location);
1907
+ session.placements.place("character", character.id, {
1908
+ locationId: location.id,
1909
+ ...place.position === void 0 ? {} : { position: place.position },
1910
+ ...place.feature === void 0 ? {} : { featureKey: place.feature }
1911
+ });
1912
+ }
1913
+ }
1914
+ for (const { id, relationships } of characters) {
1915
+ const from = session.characters.getBySourceId(id);
1916
+ for (const relation of relationships ?? []) session.relationships.upsert(from.id, session.characters.getBySourceId(relation.to).id, {
1917
+ label: relation.label,
1918
+ summary: relation.summary,
1919
+ familiarity: relation.familiarity,
1920
+ trust: relation.trust,
1921
+ affinity: relation.affinity,
1922
+ tension: relation.tension
1923
+ }, 0);
1924
+ }
2179
1925
  }
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
- });
1926
+ function populateFactions(session, factions) {
1927
+ for (const definition of factions) {
1928
+ const faction = session.factions.add({
1929
+ sourceId: definition.id,
1930
+ name: definition.name,
1931
+ aliases: definition.aliases,
1932
+ summary: definition.summary,
1933
+ description: definition.description,
1934
+ values: definition.values,
1935
+ structure: definition.structure
1936
+ });
1937
+ session.factionStates.create(faction.id, definition.start);
1938
+ for (const goal of definition.start.goals) session.factionIntents.add(faction.id, goal);
1939
+ }
1940
+ for (const definition of factions) {
1941
+ const faction = session.factions.getBySourceId(definition.id);
1942
+ for (const member of definition.members) {
1943
+ const character = session.characters.getBySourceId(member.character);
1944
+ session.factionMemberships.upsert(faction.id, character.id, member, 0);
1945
+ if (session.factionRelationships.get("character", character.id, "faction", faction.id) === void 0) session.factionRelationships.upsert("character", character.id, "faction", faction.id, {
1946
+ label: member.role || "member",
1947
+ familiarity: 1
1948
+ }, 0);
1949
+ }
1950
+ for (const relation of definition.relationships) {
1951
+ const target = relation.to.kind === "character" ? session.characters.getBySourceId(relation.to.id) : session.factions.getBySourceId(relation.to.id);
1952
+ session.factionRelationships.upsert("faction", faction.id, relation.to.kind, target.id, relation, 0);
1953
+ }
1954
+ }
2200
1955
  }
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;
1956
+ /** Give each character its authored knowledge, plus what is visible where it starts. */
1957
+ function populateKnowledge(session, characters) {
1958
+ for (const definition of characters) {
1959
+ const character = session.characters.getBySourceId(definition.id);
1960
+ for (const key of definition.knowledge?.locations ?? []) session.knowledge.learn(character.id, "location", session.locations.getBySourceId(key).id, 0);
1961
+ for (const key of definition.knowledge?.items ?? []) session.knowledge.learn(character.id, "item", session.items.getBySourceId(key).id, 0);
1962
+ for (const wanted of definition.knowledge?.exits ?? []) {
1963
+ const exit = session.locations.getExit(session.locations.getBySourceId(wanted.from).id, session.locations.getBySourceId(wanted.to).id);
1964
+ session.knowledge.learn(character.id, "exit", exit.id, 0);
1965
+ session.knowledge.learn(character.id, "location", exit.fromId, 0);
1966
+ session.knowledge.learn(character.id, "location", exit.toId, 0);
1967
+ }
1968
+ for (const key of definition.knowledge?.lore ?? []) session.knowledge.learn(character.id, "lore", session.lore.getBySourceId(key).id, 0);
1969
+ const placement = session.placements.get("character", character.id);
1970
+ if (placement === void 0) continue;
1971
+ session.knowledge.learn(character.id, "location", placement.locationId, 0, true);
1972
+ for (const exit of session.locations.exitsFrom(placement.locationId)) {
1973
+ session.knowledge.learn(character.id, "exit", exit.id, 0, true);
1974
+ session.knowledge.learn(character.id, "location", exit.toId, 0);
1975
+ }
1976
+ for (const { item } of session.items.contents({
1977
+ kind: "location",
1978
+ id: placement.locationId
1979
+ })) if (!item.hidden) session.knowledge.learn(character.id, "item", item.id, 0, true);
1980
+ for (const { item } of session.items.contents({
1981
+ kind: "character",
1982
+ id: character.id
1983
+ })) session.knowledge.learn(character.id, "item", item.id, 0, true);
1984
+ 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
1985
  }
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
1986
  }
2232
1987
  /**
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.
1988
+ * Put a world's slots and things into a new session, each where it starts, with what opens each lock. Containers come
1989
+ * before what is in them; what opens an exit is set for both directions of it.
2235
1990
  */
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
- }]);
1991
+ function populateItems(session, items, slots, locations) {
1992
+ for (const slot of slots) session.slots.upsert(slot);
1993
+ const made = /* @__PURE__ */ new Map();
1994
+ for (const definition of containersFirst(items)) {
1995
+ const { start } = definition;
1996
+ const holder = start.kind === "location" ? {
1997
+ kind: "location",
1998
+ locationId: session.locations.getBySourceId(start.location).id,
1999
+ ...start.position === void 0 ? {} : { position: start.position },
2000
+ ...start.feature === void 0 ? {} : { featureKey: start.feature }
2001
+ } : start.kind === "held" ? {
2002
+ kind: "character",
2003
+ characterId: session.characters.getBySourceId(start.character).id,
2004
+ mode: "held"
2005
+ } : start.kind === "worn" ? {
2006
+ kind: "character",
2007
+ characterId: session.characters.getBySourceId(start.character).id,
2008
+ mode: "worn",
2009
+ slot: definition.wearable,
2010
+ ...start.position === void 0 ? {} : { position: start.position }
2011
+ } : {
2012
+ kind: "item",
2013
+ itemId: made.get(start.item),
2014
+ ...start.position === void 0 ? {} : { position: start.position }
2015
+ };
2016
+ const item = session.items.add({
2017
+ sourceId: definition.id,
2018
+ name: definition.name,
2019
+ description: definition.description,
2020
+ quantity: definition.quantity,
2021
+ unique: definition.unique,
2022
+ quality: definition.quality,
2023
+ notable: definition.notable,
2024
+ hidden: definition.hidden,
2025
+ ...definition.wearable === void 0 ? {} : { wearableSlot: definition.wearable },
2026
+ ...definition.container === void 0 ? {} : { container: { state: definition.container.state } },
2027
+ ...definition.owner === void 0 ? {} : { ownerId: session.characters.getBySourceId(definition.owner).id }
2028
+ }, holder);
2029
+ if (definition.visualIdentity !== void 0) session.visualIdentities.set("item", item.id, definition.visualIdentity);
2030
+ made.set(definition.id, item.id);
2250
2031
  }
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
- });
2032
+ for (const definition of items) if (definition.container !== void 0 && definition.container.openedBy.length > 0) session.items.setOpeners({
2033
+ kind: "item",
2034
+ id: made.get(definition.id)
2035
+ }, definition.container.openedBy.map((key) => made.get(key)));
2036
+ for (const place of locations) {
2037
+ const from = session.locations.getBySourceId(place.id);
2038
+ for (const exit of place.exits) {
2039
+ if ((exit.openedBy ?? []).length === 0) continue;
2040
+ const to = session.locations.getBySourceId(exit.to);
2041
+ for (const [a, b] of [[from.id, to.id], [to.id, from.id]]) {
2042
+ const way = session.locations.getExit(a, b);
2043
+ if (way !== void 0) session.items.setOpeners({
2044
+ kind: "exit",
2045
+ id: way.id
2046
+ }, exit.openedBy.map((key) => made.get(key)));
2047
+ }
2048
+ }
2049
+ }
2050
+ }
2051
+ /** 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). */
2052
+ function populateClock(session, settings, world, wall) {
2053
+ const start = settings.mode === "real" ? wall : world?.startingTime ?? Math.floor(wall / MINUTE) * MINUTE;
2054
+ session.clock.start(settings.mode, start);
2055
+ }
2056
+ /**
2057
+ * Make the world's triggers, once everything they can name exists.
2058
+ * @throws {Error} naming each trigger that names something the world does not have.
2059
+ */
2060
+ function populateTriggers(session, definitions) {
2061
+ const keys = definitions.map((definition) => definition.key);
2062
+ const problems = definitions.flatMap((definition) => triggerReferenceProblems(session, definition, keys));
2063
+ if (problems.length > 0) throw new InvalidWorldError(`the triggers have ${problems.length} problem(s)`, problems.map((message) => ({
2064
+ path: TRIGGERS_FILE_NAME,
2065
+ message
2066
+ })));
2067
+ for (const definition of definitions) session.triggers.add(definition, "world", 0);
2068
+ }
2069
+ // src/host/worlds/scratch.ts
2070
+ /**
2071
+ * 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
2072
+ * a store has; the search a session adds is not needed.
2073
+ */
2074
+ function withScratchStory(parts, use) {
2075
+ const scratch = createSessionStore(":memory:", {
2076
+ id: "scratch",
2077
+ name: "scratch",
2078
+ world: {
2079
+ id: "scratch",
2080
+ name: "scratch"
2261
2081
  }
2262
- if (repairs.some((repair) => repair.file === file)) await atomicWrite(join(directory, file), `${JSON.stringify(document, null, 2)}\n`);
2082
+ }, { vectors: false });
2083
+ try {
2084
+ const session = scratch;
2085
+ if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
2086
+ populateLocations(session, parts.locations);
2087
+ populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
2088
+ populateItems(session, parts.items, parts.slots, parts.locations);
2089
+ populateVariables(session, parts.variables, {
2090
+ characters: parts.characters,
2091
+ items: parts.items,
2092
+ locations: parts.locations,
2093
+ values: void 0
2094
+ });
2095
+ return use(session);
2096
+ } finally {
2097
+ scratch.close();
2263
2098
  }
2264
- return repairs;
2265
2099
  }
2266
- // src/host/worlds/world-file-io.ts
2267
- const queue = new SerialQueue();
2100
+ // src/host/worlds/validated-world.ts
2268
2101
  /**
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.
2102
+ * 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.
2103
+ * @throws {InvalidWorldError} naming every problem of the first part of the world that has any.
2271
2104
  */
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;
2105
+ async function loadValidatedWorld(world) {
2106
+ const { characters, problems } = await loadCharacters(world.directory);
2107
+ if (problems.length > 0) throw new InvalidWorldError(`the characters of "${world.summary.name}" have ${problems.length} problem(s)`, problems);
2108
+ const { factions, problems: factionFileProblems } = await loadFactions(world.directory);
2109
+ if (factionFileProblems.length > 0) throw new InvalidWorldError(`the factions of "${world.summary.name}" have ${factionFileProblems.length} problem(s)`, factionFileProblems);
2110
+ const factionReferences = factionProblems(factions, characters);
2111
+ if (factionReferences.length > 0) throw new InvalidWorldError(`the factions of "${world.summary.name}" have ${factionReferences.length} problem(s)`, factionReferences.map((message) => ({
2112
+ path: world.directory,
2113
+ message
2114
+ })));
2115
+ const { locations, problems: locationProblems } = await loadLocations(world.directory);
2116
+ if (locationProblems.length > 0) throw new InvalidWorldError(`the places of "${world.summary.name}" have ${locationProblems.length} problem(s)`, locationProblems);
2117
+ const placing = startingPlaceProblems(characters, locations);
2118
+ if (placing.length > 0) throw new InvalidWorldError(`the starting places of "${world.summary.name}" have ${placing.length} problem(s)`, placing.map((message) => ({
2119
+ path: world.directory,
2120
+ message
2121
+ })));
2122
+ const { calendar, problems: calendarProblems } = await loadCalendar(world.directory);
2123
+ if (calendarProblems.length > 0) throw new InvalidWorldError(`the calendar of "${world.summary.name}" has ${calendarProblems.length} problem(s)`, calendarProblems);
2124
+ const dice = await loadDice(world.directory);
2125
+ if (dice.problems.length > 0) throw new InvalidWorldError(`the dice checks of "${world.summary.name}" have ${dice.problems.length} problem(s)`, dice.problems);
2126
+ const days = routineProblems(characters, locations, calendar);
2127
+ if (days.length > 0) throw new InvalidWorldError(`the days of the characters of "${world.summary.name}" have ${days.length} problem(s)`, days.map((message) => ({
2128
+ path: world.directory,
2129
+ message
2130
+ })));
2131
+ const { items, slots, problems: itemProblems } = await loadItems(world.directory, {
2132
+ characters: characters.map((character) => character.id),
2133
+ locations
2134
+ });
2135
+ if (itemProblems.length > 0) throw new InvalidWorldError(`the items of "${world.summary.name}" have ${itemProblems.length} problem(s)`, itemProblems);
2136
+ const authoredLore = await loadLore(world.directory);
2137
+ if (authoredLore.problems.length > 0) throw new InvalidWorldError(`the lore of "${world.summary.name}" has ${authoredLore.problems.length} problem(s)`, authoredLore.problems);
2138
+ const loreReferences = loreProblems(authoredLore.lore, {
2139
+ characters,
2140
+ factions,
2141
+ locations,
2142
+ items
2143
+ });
2144
+ if (loreReferences.length > 0) throw new InvalidWorldError(`the lore of "${world.summary.name}" has ${loreReferences.length} invalid reference(s)`, loreReferences.map((message) => ({
2145
+ path: world.directory,
2146
+ message
2147
+ })));
2148
+ const knowing = knowledgeProblems(characters, locations, items, authoredLore.lore);
2149
+ if (knowing.length > 0) throw new InvalidWorldError(`the starting knowledge of "${world.summary.name}" has ${knowing.length} problem(s)`, knowing.map((message) => ({
2150
+ path: world.directory,
2151
+ message
2152
+ })));
2153
+ const declared = await loadVariables(world.directory);
2154
+ if (declared.problems.length > 0) throw new InvalidWorldError(`the variables of "${world.summary.name}" have ${declared.problems.length} problem(s)`, declared.problems);
2155
+ const commandFile = await loadCommands(world.directory);
2156
+ if (commandFile.problems.length > 0) throw new InvalidWorldError(`the commands of "${world.summary.name}" have ${commandFile.problems.length} problem(s)`, commandFile.problems);
2157
+ const own = new Set(declared.defs.map((def) => def.key));
2158
+ const clashing = commandFile.commands.filter((command) => own.has(commandVariable(command)));
2159
+ if (clashing.length > 0) throw new InvalidWorldError(`the commands of "${world.summary.name}" have ${clashing.length} problem(s)`, clashing.map((command) => ({
2160
+ path: world.directory,
2161
+ message: `/${command.word} raises the flag ${commandVariable(command)}, which variables.json declares too: remove one`
2162
+ })));
2163
+ declared.defs = [...declared.defs, ...commandFile.commands.map(commandFlag)];
2164
+ const tracking = variableProblems({
2165
+ defs: declared.defs,
2166
+ characters,
2167
+ items,
2168
+ locations,
2169
+ values: world.variables
2170
+ });
2171
+ if (tracking.length > 0) throw new InvalidWorldError(`what "${world.summary.name}" tracks has ${tracking.length} problem(s)`, tracking.map((message) => ({
2172
+ path: world.directory,
2173
+ message
2174
+ })));
2175
+ const scripted = await loadTriggers(world.directory);
2176
+ if (scripted.problems.length > 0) throw new InvalidWorldError(`the triggers of "${world.summary.name}" have ${scripted.problems.length} problem(s)`, scripted.problems);
2177
+ const authoredPlots = await loadPlots(world.directory);
2178
+ if (authoredPlots.problems.length > 0) throw new InvalidWorldError(`the plots of "${world.summary.name}" have ${authoredPlots.problems.length} problem(s)`, authoredPlots.problems);
2179
+ const plotReferences = plotReferenceProblems(authoredPlots.plots, [
2180
+ ...characters.map((entry) => entry.id),
2181
+ ...factions.map((entry) => entry.id),
2182
+ ...locations.map((entry) => entry.id),
2183
+ ...items.map((entry) => entry.id),
2184
+ ...authoredLore.lore.map((entry) => entry.id)
2185
+ ]);
2186
+ if (plotReferences.length > 0) throw new InvalidWorldError(`the plots of "${world.summary.name}" have ${plotReferences.length} invalid participant(s)`, plotReferences.map((message) => ({
2187
+ path: world.directory,
2188
+ message
2189
+ })));
2190
+ const related = relationshipProblems(characters);
2191
+ if (related.length > 0) throw new InvalidWorldError(`the relationships of "${world.summary.name}" have ${related.length} problem(s)`, related.map((message) => ({
2192
+ path: world.directory,
2193
+ message
2194
+ })));
2195
+ withScratchStory({
2196
+ characters,
2197
+ locations,
2198
+ items,
2199
+ slots,
2200
+ variables: declared.defs,
2201
+ calendar
2202
+ }, (story) => {
2203
+ populateTriggers(story, scripted.triggers);
2284
2204
  });
2205
+ return {
2206
+ characters,
2207
+ factions,
2208
+ locations,
2209
+ items,
2210
+ slots,
2211
+ authoredLore,
2212
+ declared,
2213
+ scripted,
2214
+ authoredPlots,
2215
+ calendar,
2216
+ checks: dice.checks,
2217
+ commands: commandFile.commands
2218
+ };
2219
+ }
2220
+ // src/host/worlds/world-check.ts
2221
+ /** The most problems listed at once: the rest are named by their number. */
2222
+ const LISTED$1 = 40;
2223
+ /**
2224
+ * 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
2225
+ * 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
2226
+ * fixing those can show the next part's.
2227
+ */
2228
+ async function checkWorld(world) {
2229
+ try {
2230
+ await loadValidatedWorld(world);
2231
+ return {
2232
+ ok: true,
2233
+ problems: [],
2234
+ more: 0
2235
+ };
2236
+ } catch (error) {
2237
+ if (!(error instanceof InvalidWorldError)) throw error;
2238
+ const problems = error.problems.map((problem) => ({
2239
+ where: relative(world.directory, problem.path).split(sep).join("/") || "(the world)",
2240
+ message: problem.message
2241
+ }));
2242
+ return {
2243
+ ok: false,
2244
+ summary: error.message,
2245
+ problems: problems.slice(0, LISTED$1),
2246
+ more: Math.max(0, problems.length - LISTED$1)
2247
+ };
2248
+ }
2285
2249
  }
2286
2250
  // src/host/worlds/entity-folders.ts
2287
2251
  /** 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. */
@@ -3234,6 +3198,15 @@ const CHECK_COMMANDS = {
3234
3198
  "check-play": ["playability"]
3235
3199
  };
3236
3200
  const findingKey = (finding) => `${finding.check}\n${finding.code}\n${finding.where}\n${finding.message}`;
3201
+ /** 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. */
3202
+ const CHECK_COMMAND_DESCRIPTIONS = {
3203
+ check: "Check the world with every kit of checks",
3204
+ "check-all": "Check the world with every kit of checks",
3205
+ "check-world": "Check that the world agrees with itself",
3206
+ "check-card": "Check that the world carries what the imported card says",
3207
+ "check-quality": "Check the quality of the world: panels, style, leftovers",
3208
+ "check-play": "Check that the world can be played"
3209
+ };
3237
3210
  // src/host/checks/terms.ts
3238
3211
  const HAN = /[㐀-鿿]+/gu;
3239
3212
  /** Words of fewer letters are mostly the glue of a language, which says nothing about whether two texts share facts. */
@@ -3393,6 +3366,7 @@ function infoOf(document, startQuestions = []) {
3393
3366
  authorUrl: textOf(author["url"]),
3394
3367
  timeZone: textOf(document["time_zone"]),
3395
3368
  startingTime: textOf(document["starting_time"]),
3369
+ language: textOf(document["language"]),
3396
3370
  preset: textOf(document["preset"]),
3397
3371
  lorebooks: Array.isArray(document["lorebooks"]) ? document["lorebooks"].filter((name) => typeof name === "string") : [],
3398
3372
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
@@ -3469,6 +3443,7 @@ async function changeWorldInfo(directory, edit) {
3469
3443
  if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
3470
3444
  if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
3471
3445
  if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
3446
+ if (edit.language !== void 0) setOrRemove(document, "language", edit.language);
3472
3447
  if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
3473
3448
  if (edit.lorebooks !== void 0) {
3474
3449
  if (edit.lorebooks.length === 0) delete document["lorebooks"];
@@ -5876,6 +5851,42 @@ async function forgetJobs(directory) {
5876
5851
  force: true
5877
5852
  });
5878
5853
  }
5854
+ // src/host/import/output-ceiling.ts
5855
+ /** 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. */
5856
+ const AUTO_OUTPUT_SHARE = .1;
5857
+ const AUTO_OUTPUT_MIN = 16e3;
5858
+ const AUTO_OUTPUT_UNKNOWN = 32e3;
5859
+ const windows = /* @__PURE__ */ new Map();
5860
+ /** The most one request may write when the setting is automatic (0): a tenth of the window, at least 16 000 tokens. */
5861
+ function autoOutputCeiling(window) {
5862
+ return window === void 0 ? AUTO_OUTPUT_UNKNOWN : Math.max(AUTO_OUTPUT_MIN, Math.round(window * AUTO_OUTPUT_SHARE));
5863
+ }
5864
+ /** 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. */
5865
+ function knownOutputCeiling(configured, model) {
5866
+ if (configured > 0) return configured;
5867
+ return autoOutputCeiling(model === void 0 ? void 0 : windows.get(`${model.provider}/${model.model}`));
5868
+ }
5869
+ /** 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). */
5870
+ async function outputCeiling(configured, agent, named, signal) {
5871
+ if (configured > 0) return configured;
5872
+ const config = agent.session.requestHeader()?.config;
5873
+ const model = named ?? (config?.provider === void 0 || config.model === void 0 ? void 0 : {
5874
+ provider: config.provider,
5875
+ model: config.model
5876
+ });
5877
+ if (model === void 0) return autoOutputCeiling();
5878
+ const key = `${model.provider}/${model.model}`;
5879
+ let window = windows.get(key);
5880
+ if (window === void 0) {
5881
+ try {
5882
+ window = (await agent.ctx.llm.resolveModelInfo(model.provider, model.model, signal)).context?.contextWindow;
5883
+ } catch {
5884
+ window = void 0;
5885
+ }
5886
+ if (window !== void 0) windows.set(key, window);
5887
+ }
5888
+ return autoOutputCeiling(window);
5889
+ }
5879
5890
  // src/host/import/tools.ts
5880
5891
  const residencyOf = (agent) => agent.ctx.get("roleplayOrchestration")?.residency;
5881
5892
  const SURVEY_TOOL = "import_survey";
@@ -6083,53 +6094,64 @@ function importNotice(phase, text) {
6083
6094
  done: phase === "done" ? text("import/notice-done") : ""
6084
6095
  });
6085
6096
  }
6086
- /** 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. */
6087
- function importHooks(ctx, worlds, prompting) {
6088
- const textFor = (worldId) => (id, variables) => prompting.prompts().text(id, worldId === void 0 ? void 0 : prompting.languages().get(worldId), {
6089
- ...toolNames,
6090
- ...variables
6091
- });
6092
- const imports = /* @__PURE__ */ new Map();
6093
- const objections = /* @__PURE__ */ new Map();
6094
- const repairs = /* @__PURE__ */ new Map();
6097
+ /** 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. */
6098
+ const importTextFor = (prompting) => (worldId) => (id, variables) => prompting.prompts().text(id, worldId === void 0 ? void 0 : prompting.languages().get(worldId), {
6099
+ ...toolNames,
6100
+ ...variables
6101
+ });
6102
+ /**
6103
+ * 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
6104
+ * (`beginImport`) and gives the chat the procedure of the step the import has reached.
6105
+ */
6106
+ function importHooks(ctx, worlds, prompting, state) {
6107
+ const textFor = importTextFor(prompting);
6108
+ const { importing: imports, objections, repairs } = state;
6095
6109
  const authoring = (agent) => agent.session.header.origin === "subagent" || authoredWorldOf(agent.session.id) === void 0 ? void 0 : agent.session.id;
6096
- ctx.on("agent/pre-step", async (payload, next) => {
6097
- const decision = await next();
6098
- const chat = authoring(payload.agent);
6099
- if (decision.kind !== "enter" || payload.step !== 1 || chat === void 0) return decision;
6100
- const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
6101
- if (parseImportCommand(text) === void 0) return decision;
6102
- const worldId = authoredWorldOf(chat);
6103
- const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
6104
- const phase = record === void 0 ? void 0 : await importPhase(record.directory);
6105
- if (phase !== void 0 && phase !== "done") {
6106
- imports.set(chat, payload.turn);
6107
- objections.delete(chat);
6108
- repairs.delete(chat);
6109
- }
6110
- if (phase === "repair" && record !== void 0) await startRepair(record.directory);
6111
- return {
6112
- ...decision,
6113
- messages: [...decision.messages, createUserMessage({
6110
+ registerCommands(ctx, [{
6111
+ name: IMPORT_COMMAND.slice(1),
6112
+ description: "Import the character card waiting in this world",
6113
+ hint: "<card file> [what to do]",
6114
+ recordInput: false,
6115
+ handler: async ({ agent, rawInput }) => {
6116
+ const chat = authoring(agent);
6117
+ if (chat === void 0) return {
6118
+ kind: "error",
6119
+ text: `${IMPORT_COMMAND} runs in the authoring chat of a world`
6120
+ };
6121
+ const begun = await beginImport({
6122
+ worlds,
6123
+ text: textFor,
6124
+ state
6125
+ }, chat, importRequestOf(rawInput));
6126
+ if (!begun.ok) return {
6127
+ kind: "error",
6128
+ text: begun.reason
6129
+ };
6130
+ agent.followup(createUserMessage({
6114
6131
  content: [{
6115
6132
  type: "text",
6116
- text: importNotice(phase, textFor(worldId))
6133
+ text: begun.message
6117
6134
  }],
6118
6135
  source: { kind: "roleplay" }
6119
- })]
6120
- };
6121
- });
6136
+ }));
6137
+ return {
6138
+ kind: "success",
6139
+ text: "Importing the card…"
6140
+ };
6141
+ }
6142
+ }]);
6122
6143
  ctx.on("session/event", async (session, event) => {
6123
6144
  if (event.type !== "turn/end" || session.header.origin === "subagent") return;
6124
6145
  const worldId = authoredWorldOf(session.id);
6125
6146
  const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
6147
+ imports.delete(session.id);
6126
6148
  if (record === void 0) return;
6127
6149
  await endReview(record.directory);
6128
6150
  await settleDraft(record.directory);
6129
6151
  });
6130
- ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
6152
+ ctx.on("agent/turn-stopping", async ({ agent }) => {
6131
6153
  const chat = authoring(agent);
6132
- if (chat === void 0 || imports.get(chat) !== turn) return;
6154
+ if (chat === void 0 || !imports.has(chat)) return;
6133
6155
  const worldId = authoredWorldOf(chat);
6134
6156
  const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
6135
6157
  const phase = record === void 0 ? void 0 : await importPhase(record.directory);
@@ -6178,6 +6200,41 @@ function importHooks(ctx, worlds, prompting) {
6178
6200
  }));
6179
6201
  });
6180
6202
  }
6203
+ // src/host/import/begin.ts
6204
+ /** 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. */
6205
+ var ImportState = class {
6206
+ importing = /* @__PURE__ */ new Set();
6207
+ objections = /* @__PURE__ */ new Map();
6208
+ repairs = /* @__PURE__ */ new Map();
6209
+ };
6210
+ /**
6211
+ * 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.
6212
+ * The `/import-st` command and the plugin's own start of an import both begin here.
6213
+ */
6214
+ async function beginImport(deps, chat, request) {
6215
+ const worldId = authoredWorldOf(chat);
6216
+ const record = worldId === void 0 ? void 0 : await deps.worlds.find(worldId);
6217
+ if (record === void 0) return {
6218
+ ok: false,
6219
+ reason: "an import runs in the authoring chat of a world"
6220
+ };
6221
+ const phase = await importPhase(record.directory);
6222
+ if (phase === void 0) return {
6223
+ ok: false,
6224
+ reason: "no card is waiting to be imported in this world"
6225
+ };
6226
+ if (phase !== "done") {
6227
+ deps.state.importing.add(chat);
6228
+ deps.state.objections.delete(chat);
6229
+ deps.state.repairs.delete(chat);
6230
+ }
6231
+ if (phase === "repair") await startRepair(record.directory);
6232
+ const notice = importNotice(phase, deps.text(worldId));
6233
+ return {
6234
+ ok: true,
6235
+ message: request.trim() === "" ? notice : `${notice}\n\n${request.trim()}`
6236
+ };
6237
+ }
6181
6238
  // src/shared/import-selection.ts
6182
6239
  const MAX_PREVIEW_TEXT = 4e3;
6183
6240
  // src/host/tools/authoring-tools.ts
@@ -6219,6 +6276,6 @@ function limitAuthoringAgents(ctx, kindOf) {
6219
6276
  return await next();
6220
6277
  });
6221
6278
  }
6222
- 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 };
6279
+ export { checkWorld as $, loadWorldParts as A, UPDATE_FOLDER as At, localChanges as B, TRIGGERS_FILE_NAME as Bt, cardChanges as C, loadDice as Ct, worldFieldChanges as D, parseCalendarFile as Dt, pictureChange as E, loadCalendar as Et, editsSince as F, readSource as Ft, addressesToFetch as G, pictureOf as Gt, writeOrigin as H, ImportCardError as Ht, writeSnapshot as I, COMMANDS_FILE_NAME as It, guardedLookup as J, DICE_READINGS as Jt, candidateUrls as K, readCard as Kt, describeChanges as L, commandVariable as Lt, CHECK_COMMANDS as M, cardPieces as Mt, CHECK_COMMAND_DESCRIPTIONS as N, cardTools as Nt, editWorldInfo as O, CHARACTERS_DIR as Ot, recordProvenance as P, entitiesByPiece as Pt, writePortrait as Q, hashWorld as R, loadCommands as Rt, addressChanges as S, DICE_FILE_NAME as St, matchPieces as T, CALENDAR_FILE_NAME as Tt, CatalogueError as U, cardFormat as Ut, readOrigin as V, loadTriggers as Vt, addressKey as W, isPng as Wt, vetUrl as X, authoredWorldOf as Xt, mergeReports as Y, DICE_RESULTS as Yt, cardCharacter as Z, authoringChatSessionId 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, baseId 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, DICE_COMPARISONS 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, parseCommandsFile as zt };
6223
6280
 
6224
- //# sourceMappingURL=authoring-tools-VOaXzr_R.js.map
6281
+ //# sourceMappingURL=authoring-tools-hacA5fG-.js.map