@dsh-agentic-roleplay/core 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  2. package/lib/authoring.js +193 -227
  3. package/lib/client.js +2710 -1322
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +2 -3
  6. package/lib/deliver-BDW5WZvc.js +2262 -0
  7. package/lib/{documents-Bu5uYRZB.js → documents-DtlY2IRt.js} +958 -10
  8. package/lib/{gallery-DUeBMHQX.js → gallery-DACG5eh2.js} +2 -2
  9. package/lib/{generator-HPifO3Kk.js → generator-DGYcLMp7.js} +2 -2
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +419 -23
  12. package/lib/{narration-BRyHU0H2.js → narration-5ig7Dg28.js} +12 -2
  13. package/lib/orchestration.js +458 -342
  14. package/lib/{packs-ByP1J-zj.js → packs-CkRZDCsV.js} +51 -5
  15. package/lib/{presenter-agent-G43ODV8I.js → presenter-agent-PK9JYExk.js} +4 -4
  16. package/package.json +5 -4
  17. package/packs/scene/map.html +12 -0
  18. package/packs/scene/map.js +55 -0
  19. package/packs/scene/pack.json +11 -0
  20. package/packs/scene/strip.html +11 -0
  21. package/packs/scene/strip.js +26 -0
  22. package/packs/scene/style.css +16 -0
  23. package/prompts/en/roleplay/character-decide.md +1 -1
  24. package/prompts/en/roleplay/character-rules.md +1 -1
  25. package/prompts/en/roleplay/chronicler.md +1 -1
  26. package/prompts/en/roleplay/game-master.md +1 -1
  27. package/prompts/en/roleplay/reflection.md +9 -0
  28. package/prompts/en/roleplay/style.md +1 -1
  29. package/prompts/en/roleplay/suggester.md +1 -1
  30. package/prompts/en/translate/document.md +6 -0
  31. package/prompts/en/translate/glossary.md +5 -0
  32. package/prompts/en/translate/notice.md +2 -0
  33. package/prompts/en/world/procedure.md +1 -1
  34. package/prompts/en/world/welcome.md +1 -1
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-rules.md +1 -1
  37. package/prompts/zh/roleplay/chronicler.md +1 -1
  38. package/prompts/zh/roleplay/game-master.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/roleplay/style.md +1 -1
  41. package/prompts/zh/roleplay/suggester.md +1 -1
  42. package/prompts/zh/translate/document.md +6 -0
  43. package/prompts/zh/translate/glossary.md +5 -0
  44. package/prompts/zh/translate/notice.md +2 -0
  45. package/prompts/zh/world/procedure.md +1 -1
  46. package/prompts/zh/world/welcome.md +1 -1
  47. package/lib/access-C1nFQiyT.js +0 -12
  48. package/lib/activity-t7OBgHlc.js +0 -1386
@@ -1,11 +1,13 @@
1
- import { A as languageOf, C as errorMessage, E as PROMPTS_FOLDER, H as INTENT_HORIZONS, M as promptProblem, N as shippedLanguages, P as shippedPromptsDirectory, R as InvalidWorldError, S as readDocument, T as formatIssue, U as INTENT_STATUSES, W as INTENT_TYPES, _ as API_PREFIX, b as parsePlotsFile, j as listFiles, v as PLOTS_FILE_NAME, w as Reader, x as plotReferenceProblems, y as loadPlots } from "./packs-ByP1J-zj.js";
1
+ import { A as formatIssue, C as PLOTS_FILE_NAME, D as readDocument, E as plotReferenceProblems, F as languageOf, I as listFiles, J as INTENT_HORIZONS, L as promptProblem, O as errorMessage, R as shippedLanguages, T as parsePlotsFile, U as InvalidWorldError, X as INTENT_TYPES, Y as INTENT_STATUSES, _ as API_PREFIX, b as isStoryLanguage, j as PROMPTS_FOLDER, k as Reader, v as LANGUAGE_NAMES, w as loadPlots, x as textLanguage, y as STORY_LANGUAGES, z as shippedPromptsDirectory } from "./packs-CkRZDCsV.js";
2
2
  import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
3
- import { C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-HPifO3Kk.js";
4
- import { basename, dirname, join } from "node:path";
3
+ import { A as runChild, C as norm, S as mapLimit, T as uniqueKey, a as uploadReferenceImage, h as MEDIA_TYPES, o as addToLibrary, p as referenceImagePath, s as imageExtensionOf, t as generateReferenceImage, w as slug, y as writeImageFileMetadata } from "./generator-DGYcLMp7.js";
4
+ import { basename, dirname, join, relative, sep } from "node:path";
5
5
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
6
6
  import { createHash, randomUUID } from "node:crypto";
7
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
7
9
  import { chmod, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
8
- import { MAX_ROUTINE_WINDOWS, MINUTE, createSessionStore, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue } from "@dsh-agentic-roleplay/state";
10
+ import { MAX_ROUTINE_WINDOWS, MINUTE, MONTH_NAMES, SEASONS, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue, writeCalendar } from "@dsh-agentic-roleplay/state";
9
11
  import { lookup } from "node:dns";
10
12
  import { request } from "node:http";
11
13
  import { request as request$1 } from "node:https";
@@ -1169,6 +1171,8 @@ function readRoutine(reader) {
1169
1171
  if (from !== void 0 && from === to) window.fail("to", "a window that ends when it starts is empty");
1170
1172
  const activity = window.string("activity", { required: true });
1171
1173
  const days = window.strings("days").map((day) => day.toLowerCase());
1174
+ const on = window.strings("on");
1175
+ for (const problem of dayTokenProblems(on, "on", "any")) window.fail("on", problem.replace(/^on: /, ""));
1172
1176
  for (const day of days) if (!WEEKDAY_NAMES.includes(day)) window.fail("days", `"${day}" is not a day (${WEEKDAY_NAMES.join(", ")})`);
1173
1177
  const location = window.string("location");
1174
1178
  const feature = window.string("feature");
@@ -1179,6 +1183,7 @@ function readRoutine(reader) {
1179
1183
  if (from === void 0 || to === void 0 || activity === void 0) return [];
1180
1184
  return [{
1181
1185
  days,
1186
+ ...on.length === 0 ? {} : { on },
1182
1187
  from,
1183
1188
  to,
1184
1189
  activity,
@@ -3667,6 +3672,70 @@ async function loadLore(worldDir) {
3667
3672
  return result;
3668
3673
  }
3669
3674
  //#endregion
3675
+ //#region src/host/calendar/load.ts
3676
+ const CALENDAR_FILE_NAME = "calendar.json";
3677
+ const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
3678
+ /**
3679
+ * 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`,
3680
+ * `09-21..09-22`, `nth:mon:1`, `season:winter`, a month, a weekday); it cannot name another holiday.
3681
+ */
3682
+ function parseCalendarFile(text) {
3683
+ const issues = [];
3684
+ const reader = Reader.fromJson(text, issues);
3685
+ if (reader === void 0) return {
3686
+ ok: false,
3687
+ issues
3688
+ };
3689
+ const hemisphere = reader.oneOf("hemisphere", ["north", "south"], "north");
3690
+ const seen = /* @__PURE__ */ new Set();
3691
+ const holidays = reader.objects("holidays").flatMap((entry) => {
3692
+ const id = entry.string("id", { required: true });
3693
+ const name = entry.string("name", { required: true });
3694
+ const on = entry.strings("on");
3695
+ if (id !== void 0 && !HOLIDAY_ID.test(id)) entry.fail("id", "is made of letters, digits, \"-\" and \"_\" (at most 60)");
3696
+ if (id !== void 0 && seen.has(id)) entry.fail("id", `"${id}" is used by another holiday`);
3697
+ if (id !== void 0) seen.add(id);
3698
+ 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(", ")}`);
3699
+ for (const problem of dayTokenProblems(on, "on")) entry.fail("on", problem.replace(/^on: /, ""));
3700
+ return id === void 0 || name === void 0 ? [] : [{
3701
+ id,
3702
+ name,
3703
+ on
3704
+ }];
3705
+ });
3706
+ if (holidays.length > 60) reader.fail("holidays", `a world has at most 60 holidays`);
3707
+ return issues.length > 0 ? {
3708
+ ok: false,
3709
+ issues
3710
+ } : {
3711
+ ok: true,
3712
+ value: {
3713
+ hemisphere,
3714
+ holidays
3715
+ }
3716
+ };
3717
+ }
3718
+ /** The calendar of a world: an optional `<world>/calendar.json`; a world without one has none. */
3719
+ async function loadCalendar(worldDir) {
3720
+ const result = {
3721
+ calendar: {
3722
+ hemisphere: "north",
3723
+ holidays: []
3724
+ },
3725
+ problems: []
3726
+ };
3727
+ const file = join(worldDir, CALENDAR_FILE_NAME);
3728
+ try {
3729
+ result.calendar = await readDocument(file, parseCalendarFile, result.problems) ?? result.calendar;
3730
+ } catch (error) {
3731
+ if (error.code !== "ENOENT") result.problems.push({
3732
+ path: file,
3733
+ message: errorMessage(error)
3734
+ });
3735
+ }
3736
+ return result;
3737
+ }
3738
+ //#endregion
3670
3739
  //#region src/host/triggers/load.ts
3671
3740
  const TRIGGERS_FILE_NAME = "triggers.json";
3672
3741
  /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
@@ -3826,9 +3895,15 @@ function populateVariables(session, defs, world) {
3826
3895
  give("world", 0, world.values);
3827
3896
  }
3828
3897
  /** What is wrong with the days characters are given, found before anything is created: places that are not in the world. */
3829
- function routineProblems(characters, locations) {
3898
+ function routineProblems(characters, locations, calendar = {
3899
+ hemisphere: "north",
3900
+ holidays: []
3901
+ }) {
3830
3902
  const byId = new Map(locations.map((location) => [location.id, location]));
3903
+ const holidays = new Set(calendar.holidays.map((holiday) => holiday.id));
3831
3904
  return characters.flatMap((character) => (character.routine ?? []).flatMap((window, index) => {
3905
+ const days = dayTokenProblems(window.on ?? [], `${character.id}: routine[${index}].on`, holidays);
3906
+ if (days.length > 0) return days;
3832
3907
  if (window.location === void 0) return [];
3833
3908
  const location = byId.get(window.location);
3834
3909
  if (location === void 0) return [`${character.id}: routine[${index}].location "${window.location}" is not a place of this world`];
@@ -3836,12 +3911,17 @@ function routineProblems(characters, locations) {
3836
3911
  return [];
3837
3912
  }));
3838
3913
  }
3914
+ /** Keeps the world's calendar with the story, for the days a routine or a trigger waits for. */
3915
+ function populateCalendar(session, calendar) {
3916
+ if (calendar.holidays.length > 0 || calendar.hemisphere !== "north") writeCalendar(session.metadata, calendar);
3917
+ }
3839
3918
  /** Gives each character its recurring day, with the places by their ids in the world. */
3840
3919
  function populateRoutines(session, characters) {
3841
3920
  for (const { id, routine } of characters) {
3842
3921
  if (routine === void 0 || routine.length === 0) continue;
3843
3922
  session.routines.replace(session.characters.getBySourceId(id).id, routine.map((window) => ({
3844
3923
  days: window.days.map((day) => WEEKDAY_NAMES.indexOf(day)),
3924
+ on: window.on ?? [],
3845
3925
  start: parseTimeOfDay(window.from),
3846
3926
  end: parseTimeOfDay(window.to),
3847
3927
  activity: window.activity,
@@ -4101,7 +4181,9 @@ async function loadValidatedWorld(world) {
4101
4181
  path: world.directory,
4102
4182
  message
4103
4183
  })));
4104
- const days = routineProblems(characters, locations);
4184
+ const { calendar, problems: calendarProblems } = await loadCalendar(world.directory);
4185
+ if (calendarProblems.length > 0) throw new InvalidWorldError(`the calendar of "${world.summary.name}" has ${calendarProblems.length} problem(s)`, calendarProblems);
4186
+ const days = routineProblems(characters, locations, calendar);
4105
4187
  if (days.length > 0) throw new InvalidWorldError(`the days of the characters of "${world.summary.name}" have ${days.length} problem(s)`, days.map((message) => ({
4106
4188
  path: world.directory,
4107
4189
  message
@@ -4170,7 +4252,8 @@ async function loadValidatedWorld(world) {
4170
4252
  authoredLore,
4171
4253
  declared,
4172
4254
  scripted,
4173
- authoredPlots
4255
+ authoredPlots,
4256
+ calendar
4174
4257
  };
4175
4258
  }
4176
4259
  //#endregion
@@ -5051,6 +5134,518 @@ async function finish(ctx, world) {
5051
5134
  return result;
5052
5135
  }
5053
5136
  //#endregion
5137
+ //#region src/host/translate/terms.ts
5138
+ const STOP = /* @__PURE__ */ new Set([
5139
+ "the",
5140
+ "and",
5141
+ "for",
5142
+ "with",
5143
+ "from",
5144
+ "that",
5145
+ "this",
5146
+ "his",
5147
+ "her",
5148
+ "their",
5149
+ "she",
5150
+ "he",
5151
+ "they",
5152
+ "you",
5153
+ "your",
5154
+ "but",
5155
+ "not",
5156
+ "when",
5157
+ "where",
5158
+ "what",
5159
+ "who",
5160
+ "one",
5161
+ "two",
5162
+ "its",
5163
+ "has",
5164
+ "had",
5165
+ "was",
5166
+ "were",
5167
+ "are",
5168
+ "there",
5169
+ "then",
5170
+ "now",
5171
+ "at",
5172
+ "in",
5173
+ "on",
5174
+ "of",
5175
+ "to",
5176
+ "a",
5177
+ "an"
5178
+ ]);
5179
+ const MAX_TERMS = 40;
5180
+ const MIN_USES = 3;
5181
+ const capitalised = (word) => /^\p{Lu}[\p{L}'’-]{2,}$/u.test(word) && !STOP.has(word.toLowerCase());
5182
+ /** The parts of a name written "Place - Room": each part is a name of its own, and so is the whole. */
5183
+ function partsOfName(name) {
5184
+ return name.split(/\s+[-–—]\s+/).map((part) => part.trim()).filter((part) => part !== "");
5185
+ }
5186
+ /**
5187
+ * Words of the world that recur inside other names and texts and so have to be rendered once: the parts of names ("Iron Stag Inn" in "Iron Stag Inn - Bar") and capitalised
5188
+ * phrases of two or three words that the texts use again and again ("Iron Stag"). The most used come first; names are not repeated here.
5189
+ */
5190
+ function recurringTerms(names, texts) {
5191
+ const known = new Set(names);
5192
+ const found = /* @__PURE__ */ new Map();
5193
+ const add = (term, uses) => {
5194
+ if (!known.has(term)) found.set(term, (found.get(term) ?? 0) + uses);
5195
+ };
5196
+ for (const name of names) for (const part of partsOfName(name)) if (part !== name) add(part, MIN_USES);
5197
+ const counts = /* @__PURE__ */ new Map();
5198
+ for (const text of [...names, ...texts]) {
5199
+ const words = text.split(/[^\p{L}'’-]+/u);
5200
+ for (let at = 0; at < words.length; at += 1) for (const size of [2, 3]) {
5201
+ const phrase = words.slice(at, at + size);
5202
+ if (phrase.length !== size || !phrase.every((word) => capitalised(word.replace(/['’]s$/, "")))) continue;
5203
+ const key = phrase.join(" ").replace(/['’]s$/, "");
5204
+ counts.set(key, (counts.get(key) ?? 0) + 1);
5205
+ }
5206
+ }
5207
+ for (const [phrase, uses] of counts) if (uses >= MIN_USES) add(phrase, uses);
5208
+ return [...found].sort((a, b) => b[1] - a[1]).slice(0, MAX_TERMS).map(([term]) => term);
5209
+ }
5210
+ /** Whether `text` uses `term` as a word of its own (case as written). */
5211
+ function usesTerm(text, term) {
5212
+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5213
+ return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(text);
5214
+ }
5215
+ //#endregion
5216
+ //#region src/host/translate/prose.ts
5217
+ const rooted = (roots, paths) => roots.flatMap((root) => paths.map((path) => `${root}${path}`));
5218
+ const INTENT = [
5219
+ ".name",
5220
+ ".description",
5221
+ ".plan[]",
5222
+ ".open_threads[]",
5223
+ ".constraints[]"
5224
+ ];
5225
+ const FIELDS = {
5226
+ world: {
5227
+ names: ["name"],
5228
+ text: [
5229
+ "description",
5230
+ "rules[]",
5231
+ "metadata.tags[]",
5232
+ "opening_message",
5233
+ "opening_message[].text",
5234
+ "alternate_openings[].title",
5235
+ "alternate_openings[].text"
5236
+ ]
5237
+ },
5238
+ calendar: {
5239
+ names: ["holidays[].name"],
5240
+ text: []
5241
+ },
5242
+ variables: {
5243
+ names: [],
5244
+ text: rooted(["[]", "variables[]"], [
5245
+ ".name",
5246
+ ".description",
5247
+ ".bands[].label"
5248
+ ])
5249
+ },
5250
+ triggers: {
5251
+ names: [],
5252
+ text: rooted(["[]", "triggers[]"], [
5253
+ ".name",
5254
+ ".announce.text",
5255
+ ".effects[].text",
5256
+ ".effects[].edit.events[].text"
5257
+ ])
5258
+ },
5259
+ plots: {
5260
+ names: [],
5261
+ text: [
5262
+ "plots[].name",
5263
+ "plots[].premise",
5264
+ "plots[].themes[]",
5265
+ "plots[].stakes[]",
5266
+ "plots[].resolutions[]",
5267
+ ...["hooks", "developments"].flatMap((list) => [
5268
+ `plots[].${list}[].text`,
5269
+ `plots[].${list}[].prerequisites[]`,
5270
+ `plots[].${list}[].guidance`,
5271
+ `plots[].${list}[].avoid[]`
5272
+ ])
5273
+ ]
5274
+ },
5275
+ character: {
5276
+ names: ["name", "aliases[]"],
5277
+ text: [
5278
+ "age",
5279
+ "gender",
5280
+ "summary",
5281
+ "personality",
5282
+ "background",
5283
+ "appearance",
5284
+ "speech.style",
5285
+ "speech.examples[]",
5286
+ "start.public_state",
5287
+ "start.inner_state",
5288
+ "start.activity",
5289
+ ...INTENT.map((path) => `start.intents[]${path}`),
5290
+ "relationships[].label",
5291
+ "relationships[].summary",
5292
+ "routine[].activity"
5293
+ ]
5294
+ },
5295
+ location: {
5296
+ names: ["name", "features[].name"],
5297
+ text: [
5298
+ "description",
5299
+ "features[].description",
5300
+ "exits[].description",
5301
+ "exits[].note",
5302
+ "exits[].back_description"
5303
+ ]
5304
+ },
5305
+ item: {
5306
+ names: ["name"],
5307
+ text: ["description", "quality"]
5308
+ },
5309
+ faction: {
5310
+ names: ["name", "aliases[]"],
5311
+ text: [
5312
+ "summary",
5313
+ "description",
5314
+ "values[]",
5315
+ "structure",
5316
+ "start.public_state",
5317
+ "start.inner_state",
5318
+ ...INTENT.map((path) => `start.goals[]${path}`),
5319
+ "members[].role",
5320
+ "members[].rank",
5321
+ "relationships[].label",
5322
+ "relationships[].summary"
5323
+ ]
5324
+ },
5325
+ lore: {
5326
+ names: [],
5327
+ text: [
5328
+ "title",
5329
+ "summary",
5330
+ "body"
5331
+ ]
5332
+ }
5333
+ };
5334
+ /** The strings of a document that are words for a reader, in document order; strings with no letters need no translation and are left out. */
5335
+ function leavesOf(kind, document) {
5336
+ const fields = FIELDS[kind];
5337
+ const names = new Set(fields.names);
5338
+ const text = new Set(fields.text);
5339
+ const leaves = [];
5340
+ const visit = (value, pattern, path) => {
5341
+ if (typeof value === "string") {
5342
+ const name = names.has(pattern);
5343
+ if ((name || text.has(pattern)) && /\p{L}/u.test(value)) leaves.push({
5344
+ path,
5345
+ text: value,
5346
+ name
5347
+ });
5348
+ } else if (Array.isArray(value)) value.forEach((entry, index) => {
5349
+ visit(entry, `${pattern}[]`, [...path, index]);
5350
+ });
5351
+ else if (typeof value === "object" && value !== null) for (const [key, entry] of Object.entries(value)) visit(entry, pattern === "" ? key : `${pattern}.${key}`, [...path, key]);
5352
+ };
5353
+ visit(document, "", []);
5354
+ return leaves;
5355
+ }
5356
+ /** Puts `text` where `path` points in the document. */
5357
+ function setLeaf(document, path, text) {
5358
+ let at = document;
5359
+ for (const step of path.slice(0, -1)) at = at[step];
5360
+ at[path[path.length - 1]] = text;
5361
+ }
5362
+ const ROOT_FILES = [
5363
+ ["world.json", "world"],
5364
+ ["calendar.json", "calendar"],
5365
+ ["variables.json", "variables"],
5366
+ ["triggers.json", "triggers"],
5367
+ ["plots.json", "plots"]
5368
+ ];
5369
+ const ENTITIES = [
5370
+ [
5371
+ "characters",
5372
+ "character.json",
5373
+ "character"
5374
+ ],
5375
+ [
5376
+ "locations",
5377
+ "location.json",
5378
+ "location"
5379
+ ],
5380
+ [
5381
+ "items",
5382
+ "item.json",
5383
+ "item"
5384
+ ],
5385
+ [
5386
+ "factions",
5387
+ "faction.json",
5388
+ "faction"
5389
+ ],
5390
+ [
5391
+ "lore",
5392
+ "lore.json",
5393
+ "lore"
5394
+ ]
5395
+ ];
5396
+ async function readIfThere(file) {
5397
+ try {
5398
+ return JSON.parse(await readFile(file, "utf8"));
5399
+ } catch (error) {
5400
+ if (error.code === "ENOENT") return void 0;
5401
+ throw new Error(`${file} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
5402
+ }
5403
+ }
5404
+ /** Every file of a world that holds words for a reader. A file that does not parse stops the read: a world with a broken file is not translated. */
5405
+ async function readWorldDocuments(directory) {
5406
+ const found = [];
5407
+ for (const [file, kind] of ROOT_FILES) {
5408
+ const document = await readIfThere(join(directory, file));
5409
+ if (document !== void 0) found.push({
5410
+ file,
5411
+ kind,
5412
+ document
5413
+ });
5414
+ }
5415
+ for (const [folder, name, kind] of ENTITIES) {
5416
+ let entries;
5417
+ try {
5418
+ entries = (await readdir(join(directory, folder), { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
5419
+ } catch (error) {
5420
+ if (error.code === "ENOENT") continue;
5421
+ throw error;
5422
+ }
5423
+ for (const entry of entries) {
5424
+ const file = join(folder, entry, name);
5425
+ const document = await readIfThere(join(directory, file));
5426
+ if (document !== void 0) found.push({
5427
+ file,
5428
+ kind,
5429
+ document
5430
+ });
5431
+ }
5432
+ }
5433
+ return found;
5434
+ }
5435
+ //#endregion
5436
+ //#region src/host/translate/translate-world.ts
5437
+ /** What is not carried over to a translation: the removed things of the editor and the card import's working files. */
5438
+ const NOT_COPIED = /* @__PURE__ */ new Set([".trash", ".import"]);
5439
+ const TERMS_PER_JOB = 40;
5440
+ const TEXTS_PER_JOB = 30;
5441
+ const CHARS_PER_JOB = 5e3;
5442
+ const GLOSSARY_SHOWN = 60;
5443
+ /** A text with fewer letters than this is too short to check which language it came out in. */
5444
+ const CHECKED_LETTERS = 40;
5445
+ /** A name shorter than this is too likely to be an ordinary word to be held to the glossary. */
5446
+ const MIN_TERM = 4;
5447
+ var TranslationRefusedError = class extends Error {};
5448
+ const STRINGS = {
5449
+ type: "array",
5450
+ items: { type: "string" }
5451
+ };
5452
+ const GLOSSARY_SCHEMA = {
5453
+ type: "object",
5454
+ properties: { terms: {
5455
+ type: "array",
5456
+ items: {
5457
+ type: "object",
5458
+ properties: {
5459
+ source: { type: "string" },
5460
+ target: { type: "string" }
5461
+ },
5462
+ required: ["source", "target"],
5463
+ additionalProperties: false
5464
+ },
5465
+ description: "One entry for each name given, in the same order, with the source exactly as given."
5466
+ } },
5467
+ required: ["terms"],
5468
+ additionalProperties: false
5469
+ };
5470
+ const TEXTS_SCHEMA = {
5471
+ type: "object",
5472
+ properties: { translations: {
5473
+ ...STRINGS,
5474
+ description: "The translation of each text, in the order given."
5475
+ } },
5476
+ required: ["translations"],
5477
+ additionalProperties: false
5478
+ };
5479
+ const braces = (text) => (text.match(/\{[^{}]*\}/g) ?? []).sort().join("\0");
5480
+ const letters = (text) => text.match(/\p{L}/gu)?.length ?? 0;
5481
+ /** The language the world is written in, from the words of all its files; nothing when there are too few to tell. */
5482
+ function languageOfDocuments(documents) {
5483
+ return textLanguage(documents.flatMap((entry) => leavesOf(entry.kind, entry.document).map((leaf) => leaf.text)).join("\n"));
5484
+ }
5485
+ function batches(items, size, maxItems, maxSize) {
5486
+ const out = [];
5487
+ let current = [];
5488
+ let used = 0;
5489
+ for (const item of items) {
5490
+ if (current.length > 0 && (current.length >= maxItems || used + size(item) > maxSize)) {
5491
+ out.push(current);
5492
+ current = [];
5493
+ used = 0;
5494
+ }
5495
+ current.push(item);
5496
+ used += size(item);
5497
+ }
5498
+ if (current.length > 0) out.push(current);
5499
+ return out;
5500
+ }
5501
+ /** Why a set of translations cannot be used, or nothing. A text left in the language it was written in is not a translation. */
5502
+ function problemWith(sources, from, translations, glossary) {
5503
+ if (translations.length !== sources.length) return `${sources.length} texts were given and ${translations.length} translations came back: give exactly one for each, in order`;
5504
+ for (const [index, source] of sources.entries()) {
5505
+ const text = translations[index];
5506
+ if (text.trim() === "") return `translation ${index + 1} is empty`;
5507
+ if (braces(source) !== braces(text)) return `translation ${index + 1} must keep the text in curly braces exactly as it is: ${(source.match(/\{[^{}]*\}/g) ?? []).join(" ")}`;
5508
+ if (letters(source) >= CHECKED_LETTERS && textLanguage(source) === from && textLanguage(text) === from) return `translation ${index + 1} is still in the original language`;
5509
+ for (const [term, rendering] of glossary) if (term.length >= MIN_TERM && rendering !== term && !rendering.includes(term) && usesTerm(source, term) && usesTerm(text, term)) return `translation ${index + 1} still has "${term}": the glossary renders it "${rendering}"`;
5510
+ }
5511
+ }
5512
+ async function glossaryOf(ctx, names, vars, known = /* @__PURE__ */ new Map()) {
5513
+ const jobs = batches(names, () => 1, TERMS_PER_JOB, TERMS_PER_JOB);
5514
+ const parts = await mapLimit(jobs, ctx.concurrency, async (terms) => {
5515
+ const job = {
5516
+ persona: ctx.text("translate/glossary", vars),
5517
+ prompt: JSON.stringify({
5518
+ known: Object.fromEntries([...known].filter(([source]) => terms.some((term) => term.toLowerCase().includes(source.toLowerCase())))),
5519
+ names: terms
5520
+ }),
5521
+ result: GLOSSARY_SCHEMA,
5522
+ check: (value) => {
5523
+ if (value.terms.length !== terms.length) return `${terms.length} names were given and ${value.terms.length} came back: one for each, in order`;
5524
+ const wrong = terms.findIndex((term, index) => value.terms[index].source !== term || value.terms[index].target.trim() === "");
5525
+ return wrong === -1 ? void 0 : `entry ${wrong + 1} must repeat "${terms[wrong]}" exactly and have a translation`;
5526
+ }
5527
+ };
5528
+ return (await ctx.run(job)).terms;
5529
+ });
5530
+ return new Map(parts.flat().map((term) => [term.source, term.target.trim()]));
5531
+ }
5532
+ async function translated(ctx, texts, glossary, from, vars) {
5533
+ return (await mapLimit(batches(texts, (text) => text.length, TEXTS_PER_JOB, CHARS_PER_JOB), ctx.concurrency, async (group) => {
5534
+ const haystack = group.join("\n").toLowerCase();
5535
+ const shown = [...glossary].filter(([source]) => haystack.includes(source.toLowerCase())).slice(0, GLOSSARY_SHOWN);
5536
+ const relevant = new Map(shown);
5537
+ const job = {
5538
+ persona: ctx.text("translate/document", vars),
5539
+ prompt: JSON.stringify({
5540
+ glossary: Object.fromEntries(shown),
5541
+ texts: group.map((text, index) => ({
5542
+ n: index + 1,
5543
+ text
5544
+ }))
5545
+ }),
5546
+ result: TEXTS_SCHEMA,
5547
+ check: (value) => problemWith(group, from, value.translations, relevant)
5548
+ };
5549
+ return (await ctx.run(job)).translations;
5550
+ })).flat();
5551
+ }
5552
+ async function freeFolder(directory, suffix) {
5553
+ for (let n = 1;; n += 1) {
5554
+ const candidate = join(dirname(directory), `${basename(directory)} ${suffix}${n === 1 ? "" : ` ${n}`}`);
5555
+ try {
5556
+ await stat(candidate);
5557
+ } catch (error) {
5558
+ if (error.code === "ENOENT") return candidate;
5559
+ throw error;
5560
+ }
5561
+ }
5562
+ }
5563
+ async function listedIn(directory, names) {
5564
+ const present = new Set(await readdir(directory));
5565
+ return names.filter((name) => present.has(name));
5566
+ }
5567
+ /**
5568
+ * Makes a copy of a world in another language, next to it: the names first, so that every file calls each person, place and thing the same, then the words of each file.
5569
+ * The original is never changed. The copy gets an id of its own and is checked as a story start would check it.
5570
+ */
5571
+ async function translateWorld(ctx, worlds, source, to, told) {
5572
+ const documents = await readWorldDocuments(source.directory);
5573
+ const from = languageOfDocuments(documents);
5574
+ if (from === void 0) throw new TranslationRefusedError("there is too little text in this world to tell which language it is written in");
5575
+ if (from === to) throw new TranslationRefusedError(`this world is already written in ${LANGUAGE_NAMES[to].en}`);
5576
+ const vars = {
5577
+ from: LANGUAGE_NAMES[from][told],
5578
+ to: LANGUAGE_NAMES[to][told]
5579
+ };
5580
+ const leaves = documents.map((entry) => ({
5581
+ entry,
5582
+ leaves: leavesOf(entry.kind, entry.document)
5583
+ }));
5584
+ const names = [...new Set(leaves.flatMap((item) => item.leaves.filter((leaf) => leaf.name).map((leaf) => leaf.text)))];
5585
+ ctx.say(`translating ${names.length} names`);
5586
+ const prose = leaves.flatMap((item) => item.leaves.filter((leaf) => !leaf.name).map((leaf) => leaf.text));
5587
+ const recurring = from === "en" ? recurringTerms(names, prose) : [];
5588
+ const parts = await glossaryOf(ctx, recurring, vars);
5589
+ const glossary = await glossaryOf(ctx, names, vars, parts);
5590
+ for (const [term, rendering] of parts) glossary.set(term, rendering);
5591
+ let texts = 0;
5592
+ for (const { entry, leaves: own } of leaves) {
5593
+ const words = own.filter((leaf) => !leaf.name);
5594
+ for (const leaf of own.filter((item) => item.name)) setLeaf(entry.document, leaf.path, glossary.get(leaf.text) ?? leaf.text);
5595
+ if (words.length === 0) continue;
5596
+ ctx.say(`translating ${entry.file}`);
5597
+ const result = await translated(ctx, words.map((leaf) => leaf.text), glossary, from, vars);
5598
+ for (const [index, leaf] of words.entries()) setLeaf(entry.document, leaf.path, result[index]);
5599
+ texts += words.length;
5600
+ }
5601
+ for (const { entry, leaves: own } of leaves) {
5602
+ const document = entry.document;
5603
+ if (entry.kind !== "character" && entry.kind !== "faction") continue;
5604
+ const original = own.find((leaf) => leaf.name && leaf.path.length === 1 && leaf.path[0] === "name")?.text;
5605
+ const aliases = Array.isArray(document["aliases"]) ? document["aliases"] : [];
5606
+ if (original !== void 0 && original !== document["name"] && !aliases.includes(original)) document["aliases"] = [...aliases, original];
5607
+ }
5608
+ const id = randomUUID();
5609
+ const destination = await freeFolder(source.directory, to);
5610
+ await cp(source.directory, destination, {
5611
+ recursive: true,
5612
+ filter: (path) => !NOT_COPIED.has(relative(source.directory, path).split(sep)[0])
5613
+ });
5614
+ for (const entry of documents) {
5615
+ const document = entry.kind === "world" ? (({ id: _old, ...rest }) => ({
5616
+ id,
5617
+ ...rest
5618
+ }))(entry.document) : entry.document;
5619
+ await writeFile(join(destination, entry.file), `${JSON.stringify(document, null, 2)}\n`);
5620
+ }
5621
+ const payload = await worlds.list({ refresh: true });
5622
+ const made = payload.worlds.find((world) => world.id === id);
5623
+ if (made === void 0) throw new Error(`the translated world was written to ${destination} but the catalogue does not list it: ${payload.problems.map((problem) => problem.message).join("; ")}`);
5624
+ const record = await worlds.find(id);
5625
+ const problems = [];
5626
+ if (record !== void 0) try {
5627
+ await loadValidatedWorld(record);
5628
+ } catch (error) {
5629
+ if (!(error instanceof InvalidWorldError)) throw error;
5630
+ problems.push(...error.problems.map((problem) => `${relative(destination, problem.path) || "."}: ${problem.message}`));
5631
+ }
5632
+ return {
5633
+ worldId: id,
5634
+ name: made.name,
5635
+ folder: basename(destination),
5636
+ documents: documents.length,
5637
+ texts,
5638
+ names: names.length + recurring.length,
5639
+ problems,
5640
+ copiedAsIs: await listedIn(source.directory, [
5641
+ "prompts",
5642
+ "ui",
5643
+ "images",
5644
+ "media"
5645
+ ])
5646
+ };
5647
+ }
5648
+ //#endregion
5054
5649
  //#region src/shared/authoring-chat.ts
5055
5650
  const PREFIX = "world-author-";
5056
5651
  /** Stable DSH chat identity for the authoring conversation of one world. */
@@ -5069,6 +5664,318 @@ function authoredWorldOf(chatSessionId) {
5069
5664
  }
5070
5665
  }
5071
5666
  //#endregion
5667
+ //#region src/host/import/tools.ts
5668
+ const SURVEY_TOOL = "import_survey";
5669
+ const BUILD_TOOL = "import_build";
5670
+ const FINISH_TOOL = "import_finish";
5671
+ /** How many times a turn that has not finished the import is sent back to it. */
5672
+ const MAX_OBJECTIONS = 3;
5673
+ /** A model call that fails is made once more before the piece it was for is given up. */
5674
+ const ATTEMPTS = 2;
5675
+ const CARD = `${IMPORT_FOLDER}/card.json`;
5676
+ const cardParameter = {
5677
+ type: "string",
5678
+ required: true,
5679
+ description: `The card to import: the path that follows /import-st in the person's message (${CARD}).`
5680
+ };
5681
+ /** A model that is asked for a tool with nothing to fill in tends to write its name as text instead of calling it: naming the card gives it something to say. */
5682
+ function checkedCard(args) {
5683
+ if (args.card.trim() !== CARD) throw new Error(`the card to import is ${CARD}`);
5684
+ }
5685
+ const output = (render) => ({
5686
+ schema: { type: "json" },
5687
+ render: (_args, value) => [{
5688
+ type: "text",
5689
+ text: render(value)
5690
+ }]
5691
+ });
5692
+ const json = (value) => JSON.parse(JSON.stringify(value));
5693
+ /** The runner of an import: every job is a narrow agent below the chat's own, on the chat's model. */
5694
+ function contextOf(exec, settings, text) {
5695
+ const agent = exec.agent;
5696
+ if (agent === void 0) throw new Error("the import tools can only be called by an agent");
5697
+ const run = async (job) => {
5698
+ for (let attempt = 1;; attempt += 1) try {
5699
+ return await runChild({
5700
+ parent: agent,
5701
+ signal: exec.signal,
5702
+ persona: job.persona,
5703
+ prompt: job.prompt,
5704
+ result: job.result,
5705
+ ...job.check === void 0 ? {} : { beforeSubmit: (value) => job.check?.(value) },
5706
+ maxTokens: settings.maxTokens,
5707
+ sampling: {
5708
+ temperature: settings.temperature,
5709
+ toolChoice: "required"
5710
+ },
5711
+ ...settings.reasoning === "" ? {} : { reasoningEffort: settings.reasoning }
5712
+ });
5713
+ } catch (error) {
5714
+ if (exec.signal.aborted || attempt >= ATTEMPTS) throw error;
5715
+ }
5716
+ };
5717
+ return {
5718
+ run,
5719
+ concurrency: settings.concurrency,
5720
+ text,
5721
+ say: () => void 0
5722
+ };
5723
+ }
5724
+ async function worldOf(worlds, exec) {
5725
+ const chat = exec.agent?.session.id;
5726
+ const worldId = chat === void 0 ? void 0 : authoredWorldOf(chat);
5727
+ if (worldId === void 0) throw new Error("the import tools are available only in a world authoring chat");
5728
+ const record = await worlds.find(worldId);
5729
+ if (record === void 0) throw new Error(`the authored world "${worldId}" no longer exists`);
5730
+ return {
5731
+ id: worldId,
5732
+ directory: record.directory
5733
+ };
5734
+ }
5735
+ const toolNames = {
5736
+ survey: SURVEY_TOOL,
5737
+ build: BUILD_TOOL,
5738
+ finish: FINISH_TOOL
5739
+ };
5740
+ /** The three steps of an import, as tools of the authoring chat. They do their work in agents of their own, one narrow job each. */
5741
+ function importTools(worlds, settings, prompting) {
5742
+ /** Runs one step for the world of the calling chat; what the model should do next is told in the result, in the person's language. */
5743
+ const step = async (exec, work, next) => {
5744
+ const world = await worldOf(worlds, exec);
5745
+ const language = prompting.languages().get(world.id);
5746
+ const text = (id, variables) => prompting.prompts().text(id, language, {
5747
+ ...toolNames,
5748
+ ...variables
5749
+ });
5750
+ const result = await work(contextOf(exec, settings(), text), world.directory);
5751
+ return json({
5752
+ ...result,
5753
+ next: next(text, result)
5754
+ });
5755
+ };
5756
+ return [
5757
+ defineTool({
5758
+ name: SURVEY_TOOL,
5759
+ description: "Step 1 of importing a character card into this world: read every piece of the card, say what each is (character, place, background, instruction…), and list who and what the world is made of. Takes a few minutes. Only in an import turn.",
5760
+ parameters: { card: cardParameter },
5761
+ output: output((value) => JSON.stringify(value, null, 1)),
5762
+ isConcurrencySafe: () => false,
5763
+ async execute(args, exec) {
5764
+ checkedCard(args);
5765
+ return await step(exec, survey, (text) => text("import/next-survey"));
5766
+ }
5767
+ }),
5768
+ defineTool({
5769
+ name: BUILD_TOOL,
5770
+ description: "Step 2 of importing a character card: write every character, place, organisation, object and background entry from the pieces of the card that are about it. Takes several minutes. Run after the survey.",
5771
+ parameters: { card: cardParameter },
5772
+ output: output((value) => JSON.stringify(value, null, 1)),
5773
+ isConcurrencySafe: () => false,
5774
+ async execute(args, exec) {
5775
+ checkedCard(args);
5776
+ return await step(exec, build, (text) => text("import/next-build"));
5777
+ }
5778
+ }),
5779
+ defineTool({
5780
+ name: FINISH_TOOL,
5781
+ description: "Step 3 of importing a character card: check that the whole world would start, write it into the world together with its description, tags, opening and cover, and report what was imported. Nothing is written when the world would not start; the problems are returned. Run after the build.",
5782
+ parameters: { card: cardParameter },
5783
+ output: output((value) => JSON.stringify(value, null, 1)),
5784
+ isConcurrencySafe: () => false,
5785
+ async execute(args, exec) {
5786
+ checkedCard(args);
5787
+ return await step(exec, finish, (text, result) => text(result.ok ? "import/finish-ok" : "import/finish-failed"));
5788
+ }
5789
+ })
5790
+ ];
5791
+ }
5792
+ /** The procedure of an import turn, told to the chat in place of what it does for any other message. */
5793
+ function importNotice(phase, text) {
5794
+ if (phase === void 0) return text("import/notice-missing");
5795
+ return text("import/notice", {
5796
+ card: CARD,
5797
+ phase,
5798
+ done: phase === "done" ? text("import/notice-done") : ""
5799
+ });
5800
+ }
5801
+ /** 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. */
5802
+ function importHooks(ctx, worlds, prompting) {
5803
+ const textFor = (worldId) => (id, variables) => prompting.prompts().text(id, worldId === void 0 ? void 0 : prompting.languages().get(worldId), {
5804
+ ...toolNames,
5805
+ ...variables
5806
+ });
5807
+ const imports = /* @__PURE__ */ new Map();
5808
+ const objections = /* @__PURE__ */ new Map();
5809
+ const authoring = (agent) => agent.session.header.origin === "subagent" || authoredWorldOf(agent.session.id) === void 0 ? void 0 : agent.session.id;
5810
+ ctx.on("agent/pre-step", async (payload, next) => {
5811
+ const decision = await next();
5812
+ const chat = authoring(payload.agent);
5813
+ if (decision.kind !== "enter" || payload.step !== 1 || chat === void 0) return decision;
5814
+ if (parseImportCommand(payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n")) === void 0) return decision;
5815
+ const worldId = authoredWorldOf(chat);
5816
+ const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
5817
+ const phase = record === void 0 ? void 0 : await importPhase(record.directory);
5818
+ if (phase !== void 0 && phase !== "done") {
5819
+ imports.set(chat, payload.turn);
5820
+ objections.delete(chat);
5821
+ }
5822
+ return {
5823
+ ...decision,
5824
+ messages: [...decision.messages, createUserMessage({
5825
+ content: [{
5826
+ type: "text",
5827
+ text: importNotice(phase, textFor(worldId))
5828
+ }],
5829
+ source: { kind: "roleplay" }
5830
+ })]
5831
+ };
5832
+ });
5833
+ ctx.on("session/event", async (session, event) => {
5834
+ if (event.type !== "turn/end" || session.header.origin === "subagent") return;
5835
+ const worldId = authoredWorldOf(session.id);
5836
+ const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
5837
+ if (record !== void 0) await endReview(record.directory);
5838
+ });
5839
+ ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
5840
+ const chat = authoring(agent);
5841
+ if (chat === void 0 || imports.get(chat) !== turn) return;
5842
+ const worldId = authoredWorldOf(chat);
5843
+ const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
5844
+ const phase = record === void 0 ? void 0 : await importPhase(record.directory);
5845
+ if (phase === void 0 || phase === "done") {
5846
+ imports.delete(chat);
5847
+ return;
5848
+ }
5849
+ const told = objections.get(chat) ?? 0;
5850
+ if (told >= MAX_OBJECTIONS) {
5851
+ imports.delete(chat);
5852
+ return;
5853
+ }
5854
+ objections.set(chat, told + 1);
5855
+ const next = phase === "ready" ? SURVEY_TOOL : phase === "surveyed" ? BUILD_TOOL : FINISH_TOOL;
5856
+ agent.steer(createUserMessage({
5857
+ content: [{
5858
+ type: "text",
5859
+ text: textFor(worldId)("import/steer", {
5860
+ phase,
5861
+ next,
5862
+ card: CARD
5863
+ })
5864
+ }],
5865
+ source: { kind: "roleplay" }
5866
+ }));
5867
+ });
5868
+ }
5869
+ //#endregion
5870
+ //#region src/host/translate/tools.ts
5871
+ const TRANSLATE_TOOL = "translate_world";
5872
+ /** The message that has the authoring chat translate its world, in the language of the person who asked. */
5873
+ function translateMessage(text, to, language) {
5874
+ return text("translate/notice", {
5875
+ tool: TRANSLATE_TOOL,
5876
+ code: to,
5877
+ to: to === "zh" ? language === "zh" ? "中文" : "Chinese" : language === "zh" ? "英文" : "English"
5878
+ });
5879
+ }
5880
+ /** The tool of the authoring chat that translates the chat's world into a copy in another language. */
5881
+ function translateTools(worlds, settings, prompting) {
5882
+ return [defineTool({
5883
+ name: TRANSLATE_TOOL,
5884
+ description: "Makes a translated copy of this world, next to it, in another language: its names first, so every file calls each person, place and thing the same, then the words of every file. The world itself is not changed. Takes several minutes. Use it only when the person asked for a translation.",
5885
+ parameters: { language: {
5886
+ type: "string",
5887
+ required: true,
5888
+ enum: [...STORY_LANGUAGES],
5889
+ description: "The language to translate into: en or zh."
5890
+ } },
5891
+ output: {
5892
+ schema: { type: "json" },
5893
+ render: (_args, value) => [{
5894
+ type: "text",
5895
+ text: JSON.stringify(value, null, 1)
5896
+ }]
5897
+ },
5898
+ isConcurrencySafe: () => false,
5899
+ async execute(args, exec) {
5900
+ if (!isStoryLanguage(args.language)) throw new Error(`language must be one of: ${STORY_LANGUAGES.join(", ")}`);
5901
+ const world = await worldOf(worlds, exec);
5902
+ const told = prompting.languages().get(world.id);
5903
+ const text = (id, variables) => prompting.prompts().text(id, told, variables);
5904
+ const report = await translateWorld(contextOf(exec, settings(), text), worlds, world, args.language, told.startsWith("zh") ? "zh" : "en");
5905
+ return JSON.parse(JSON.stringify(report));
5906
+ }
5907
+ })];
5908
+ }
5909
+ //#endregion
5910
+ //#region src/host/triggers/parts.ts
5911
+ /** What the files of a world say it has, for checking what a trigger names. @throws {InvalidEditProblems} when those files have problems of their own: they are fixed first. */
5912
+ async function loadWorldParts(directory) {
5913
+ const { characters, problems: characterProblems } = await loadCharacters(directory);
5914
+ const { locations, problems: locationProblems } = await loadLocations(directory);
5915
+ const { items, slots, problems: itemProblems } = await loadItems(directory, {
5916
+ characters: characters.map((character) => character.id),
5917
+ locations
5918
+ });
5919
+ const { defs, problems: variableProblems } = await loadVariables(directory);
5920
+ const { calendar, problems: calendarProblems } = await loadCalendar(directory);
5921
+ const problems = [
5922
+ ...characterProblems,
5923
+ ...locationProblems,
5924
+ ...itemProblems,
5925
+ ...variableProblems,
5926
+ ...calendarProblems
5927
+ ];
5928
+ if (problems.length > 0) throw new InvalidEditProblems([`the world's other files have problems that come first: ${problems.map((problem) => `${problem.path}: ${problem.message}`).join("; ")}`]);
5929
+ return {
5930
+ characters,
5931
+ locations,
5932
+ items,
5933
+ slots,
5934
+ variables: defs,
5935
+ calendar
5936
+ };
5937
+ }
5938
+ //#endregion
5939
+ //#region src/host/triggers/check.ts
5940
+ /**
5941
+ * What each trigger names that the world does not have (a character, place, item or variable in its condition, its cues or the words of a
5942
+ * cue), found as a session start finds it: against a scratch story made from the world's files. Triggers that wait for each other count
5943
+ * as there. @returns the problems by trigger key; a trigger with none is not in it.
5944
+ */
5945
+ function triggerProblemsOf(parts, definitions) {
5946
+ const found = /* @__PURE__ */ new Map();
5947
+ if (definitions.length === 0) return found;
5948
+ const scratch = createSessionStore(":memory:", {
5949
+ id: "scratch",
5950
+ name: "scratch",
5951
+ world: {
5952
+ id: "scratch",
5953
+ name: "scratch"
5954
+ }
5955
+ }, { vectors: false });
5956
+ try {
5957
+ const session = scratch;
5958
+ if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
5959
+ populateLocations(session, parts.locations);
5960
+ populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
5961
+ populateItems(session, parts.items, parts.slots, parts.locations);
5962
+ populateVariables(session, parts.variables, {
5963
+ characters: parts.characters,
5964
+ items: parts.items,
5965
+ locations: parts.locations,
5966
+ values: void 0
5967
+ });
5968
+ const keys = definitions.map((definition) => definition.key);
5969
+ for (const definition of definitions) {
5970
+ const problems = triggerReferenceProblems(scratch, definition, keys).map((problem) => problem.slice(definition.key.length + 2));
5971
+ if (problems.length > 0) found.set(definition.key, problems);
5972
+ }
5973
+ } finally {
5974
+ scratch.close();
5975
+ }
5976
+ return found;
5977
+ }
5978
+ //#endregion
5072
5979
  //#region src/host/worlds/world-editor.ts
5073
5980
  function stateOf(world, definition, names) {
5074
5981
  const { start } = definition;
@@ -5115,6 +6022,34 @@ function stateOf(world, definition, names) {
5115
6022
  }))
5116
6023
  };
5117
6024
  }
6025
+ /** The triggers of the world's file as the editor shows them, with what each names that the world does not have; or why the file cannot be shown. */
6026
+ function triggersOf(parts, scripted) {
6027
+ if (scripted.problems.length > 0) return {
6028
+ triggers: [],
6029
+ triggersProblem: scripted.problems.map((problem) => problem.message).join("; ")
6030
+ };
6031
+ const view = (problems) => scripted.triggers.map((definition) => ({
6032
+ key: definition.key,
6033
+ name: definition.name,
6034
+ when: definition.condition,
6035
+ effects: definition.effects,
6036
+ repeat: definition.repeat,
6037
+ priority: definition.priority,
6038
+ ...definition.cooldownSeconds === void 0 ? {} : { cooldownSeconds: definition.cooldownSeconds },
6039
+ ...definition.chance === void 0 ? {} : { chance: definition.chance },
6040
+ ...definition.expires === void 0 ? {} : { expires: definition.expires },
6041
+ announced: definition.announce !== void 0,
6042
+ problems: problems.get(definition.key) ?? []
6043
+ }));
6044
+ try {
6045
+ return { triggers: view(triggerProblemsOf(parts, scripted.triggers)) };
6046
+ } catch (error) {
6047
+ return {
6048
+ triggers: view(/* @__PURE__ */ new Map()),
6049
+ triggersProblem: `what the triggers name could not be checked, because the rest of the world has a problem: ${error instanceof Error ? error.message : String(error)}`
6050
+ };
6051
+ }
6052
+ }
5118
6053
  /** The characters of a world as they start, and the places they can start in. */
5119
6054
  async function readWorldEditor(world) {
5120
6055
  const [{ characters }, { locations }, { factions }, { lore }, { plots }] = await Promise.all([
@@ -5124,10 +6059,21 @@ async function readWorldEditor(world) {
5124
6059
  loadLore(world.directory),
5125
6060
  loadPlots(world.directory)
5126
6061
  ]);
5127
- const { items } = await loadItems(world.directory, {
6062
+ const { items, slots } = await loadItems(world.directory, {
5128
6063
  characters: characters.map((character) => character.id),
5129
6064
  locations
5130
6065
  });
6066
+ const scripted = await loadTriggers(world.directory);
6067
+ const declared = await loadVariables(world.directory);
6068
+ const { calendar } = await loadCalendar(world.directory);
6069
+ const { triggers, triggersProblem } = triggersOf({
6070
+ characters,
6071
+ locations,
6072
+ items,
6073
+ slots,
6074
+ variables: declared.defs,
6075
+ calendar
6076
+ }, scripted);
5131
6077
  const names = new Map(locations.map((location) => [location.id, location.name]));
5132
6078
  const characterNames = new Map(characters.map((character) => [character.id, character.name]));
5133
6079
  const itemNames = new Map(items.map((item) => [item.id, item.name]));
@@ -5296,6 +6242,8 @@ async function readWorldEditor(world) {
5296
6242
  })),
5297
6243
  sources: entry.sources
5298
6244
  })),
6245
+ triggers,
6246
+ ...triggersProblem === void 0 ? {} : { triggersProblem },
5299
6247
  plots: plots.map((definition) => ({ definition })),
5300
6248
  relations
5301
6249
  };
@@ -5923,6 +6871,6 @@ async function deleteAuthoredEntity(world, kind, key) {
5923
6871
  return destination;
5924
6872
  }
5925
6873
  //#endregion
5926
- export { variableProblems as $, populateCharacters as A, routineProblems as B, endReview as C, markReady as D, isReviewing as E, populateLocations as F, subfolders as G, loadItems as H, populateLore as I, listWorldPrompts as J, PROSE_PROMPTS as K, populateRoutines as L, populateFactions as M, populateItems as N, survey as O, populateKnowledge as P, parseVariablesFile as Q, populateTriggers as R, build as S, importPhase as T, CHARACTERS_DIR as U, loadLocations as V, loadCharacters as W, writeWorldPrompt as X, readWorldPrompt as Y, VARIABLES_FILE_NAME as Z, replaceFile$1 as _, parseImportCommand as _t, replaceAuthoredEntity as a, parseChoices as at, authoredWorldOf as b, editWorldLore as c, parseWorldInfoEdit as ct, editWorldPlots as d, parseFactionEdit as dt, CHARACTER_FILE_NAME as et, editWorldRelation as f, parseLoreEdit as ft, readWorldEditor as g, IMPORT_COMMAND as gt, generateWorldCharacterPortrait as h, parseThingEdit as ht, readAuthoredEntityDocument as i, ImportStore as it, populateClock as j, loadValidatedWorld as k, editWorldNarrationVoice as l, InvalidEditProblems as lt, entityFolder as m, parseRelationEdit as mt, createAuthoredEntity as n, IMPORT_FOLDER as nt, editWorldCharacter as o, WORLD_FILE_NAME as ot, editWorldThing as p, parsePlaceEdit as pt, deleteWorldPrompt as q, deleteAuthoredEntity as r, ImportNotFoundError as rt, editWorldFaction as s, parseWorldFile as st, AUTHORED_ENTITY_KINDS as t, parseCharacterFile as tt, editWorldPlace as u, parseCharacterEdit as ut, uploadWorldCharacterPortrait as v, finish as w, authoringChatSessionId as x, worldCharacterPortraitFile as y, populateVariables as z };
6874
+ export { subfolders as $, isReviewing as A, populateLore as B, translateTools as C, parseThingEdit as Ct, authoringChatSessionId as D, authoredWorldOf as E, populateClock as F, TRIGGERS_FILE_NAME as G, populateTriggers as H, populateFactions as I, parseCalendarFile as J, CALENDAR_FILE_NAME as K, populateItems as L, loadValidatedWorld as M, populateCalendar as N, languageOfDocuments as O, populateCharacters as P, loadCharacters as Q, populateKnowledge as R, translateMessage as S, parseRelationEdit as St, importTools as T, populateVariables as U, populateRoutines as V, routineProblems as W, loadItems as X, loadLocations as Y, CHARACTERS_DIR as Z, replaceFile$1 as _, InvalidEditProblems as _t, replaceAuthoredEntity as a, VARIABLES_FILE_NAME as at, triggerProblemsOf as b, parseLoreEdit as bt, editWorldLore as c, CHARACTER_FILE_NAME as ct, editWorldPlots as d, ImportNotFoundError as dt, PROSE_PROMPTS as et, editWorldRelation as f, ImportStore as ft, readWorldEditor as g, parseWorldInfoEdit as gt, generateWorldCharacterPortrait as h, parseWorldFile as ht, readAuthoredEntityDocument as i, writeWorldPrompt as it, markReady as j, readWorldDocuments as k, editWorldNarrationVoice as l, parseCharacterFile as lt, entityFolder as m, WORLD_FILE_NAME as mt, createAuthoredEntity as n, listWorldPrompts as nt, editWorldCharacter as o, parseVariablesFile as ot, editWorldThing as p, parseChoices as pt, loadCalendar as q, deleteAuthoredEntity as r, readWorldPrompt as rt, editWorldFaction as s, variableProblems as st, AUTHORED_ENTITY_KINDS as t, deleteWorldPrompt as tt, editWorldPlace as u, IMPORT_FOLDER as ut, uploadWorldCharacterPortrait as v, parseCharacterEdit as vt, importHooks as w, IMPORT_COMMAND as wt, loadWorldParts as x, parsePlaceEdit as xt, worldCharacterPortraitFile as y, parseFactionEdit as yt, populateLocations as z };
5927
6875
 
5928
- //# sourceMappingURL=documents-Bu5uYRZB.js.map
6876
+ //# sourceMappingURL=documents-DtlY2IRt.js.map