@dsh-agentic-roleplay/core 0.3.0 → 0.3.2

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 (41) hide show
  1. package/lib/authoring.js +18 -223
  2. package/lib/client.js +1838 -489
  3. package/lib/client.js.map +1 -1
  4. package/lib/compaction.js +1 -1
  5. package/lib/deliver-BSsDtF6X.js +3443 -0
  6. package/lib/{documents-7GMc5NnW.js → documents-B5XAdfo2.js} +992 -14
  7. package/lib/{gallery-DUeBMHQX.js → gallery-DS5-qH9F.js} +2 -2
  8. package/lib/{generator-HPifO3Kk.js → generator-BzeepLd2.js} +3 -3
  9. package/lib/images.js +3 -3
  10. package/lib/index.js +351 -13
  11. package/lib/narration-DK2kiIjE.js +141 -0
  12. package/lib/orchestration.js +867 -1547
  13. package/lib/{packs-alJTiDM2.js → packs-BCGK9KZV.js} +51 -7
  14. package/lib/{presenter-agent-PX1WVaJB.js → presenter-agent-Cp-J0onD.js} +3 -3
  15. package/lib/{narration-CKZTk5UE.js → settings-CA6icLL_.js} +158 -142
  16. package/package.json +4 -4
  17. package/packs/scene/strip.js +1 -1
  18. package/prompts/en/roleplay/character-decide.md +1 -1
  19. package/prompts/en/roleplay/character-rules.md +1 -1
  20. package/prompts/en/roleplay/chronicler.md +1 -1
  21. package/prompts/en/roleplay/dice.md +7 -0
  22. package/prompts/en/roleplay/game-master.md +3 -1
  23. package/prompts/en/roleplay/reflection.md +4 -2
  24. package/prompts/en/roleplay/style.md +1 -1
  25. package/prompts/en/roleplay/suggester.md +1 -1
  26. package/prompts/en/translate/document.md +6 -0
  27. package/prompts/en/translate/glossary.md +5 -0
  28. package/prompts/en/translate/notice.md +2 -0
  29. package/prompts/zh/roleplay/character-decide.md +1 -1
  30. package/prompts/zh/roleplay/character-rules.md +1 -1
  31. package/prompts/zh/roleplay/chronicler.md +1 -1
  32. package/prompts/zh/roleplay/dice.md +7 -0
  33. package/prompts/zh/roleplay/game-master.md +3 -1
  34. package/prompts/zh/roleplay/reflection.md +4 -2
  35. package/prompts/zh/roleplay/style.md +1 -1
  36. package/prompts/zh/roleplay/suggester.md +1 -1
  37. package/prompts/zh/translate/document.md +6 -0
  38. package/prompts/zh/translate/glossary.md +5 -0
  39. package/prompts/zh/translate/notice.md +2 -0
  40. package/lib/deliver--uMhC6oO.js +0 -1878
  41. package/lib/src-CWTNeL6Y.js +0 -128
@@ -1,11 +1,13 @@
1
- import { A as languageOf, C as errorMessage, E as PROMPTS_FOLDER, G as INTENT_TYPES, M as promptProblem, N as shippedLanguages, P as shippedPromptsDirectory, R as InvalidWorldError, S as readDocument, T as formatIssue, U as INTENT_HORIZONS, W as INTENT_STATUSES, _ 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-alJTiDM2.js";
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";
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-BCGK9KZV.js";
2
+ import { c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, s as VARIABLE_KINDS } from "./settings-CA6icLL_.js";
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-BzeepLd2.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, checkProblems, 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";
@@ -111,6 +113,25 @@ const WEEKDAY_NAMES = [
111
113
  "sat"
112
114
  ];
113
115
  //#endregion
116
+ //#region ../dsh-roleplay-model/src/dice.ts
117
+ /** What a band of a check makes of an attempt; the same three results a round's outcome has. */
118
+ const DICE_RESULTS = [
119
+ "succeeded",
120
+ "partial",
121
+ "failed"
122
+ ];
123
+ /** How a roll is read: by its total, or by how many of the dice came up high enough. */
124
+ const DICE_READINGS = ["total", "successes"];
125
+ /**
126
+ * What the value is compared with: `absolute` reads the value itself, `over` the amount by which it beats the target
127
+ * (a difficulty to meet or exceed), `under` the amount by which it stays below the target (a skill to roll under).
128
+ */
129
+ const DICE_COMPARISONS = [
130
+ "absolute",
131
+ "over",
132
+ "under"
133
+ ];
134
+ //#endregion
114
135
  //#region ../dsh-roleplay-model/src/lore.ts
115
136
  const LORE_KINDS = [
116
137
  "history",
@@ -717,7 +738,7 @@ function parseWorldInfoEdit(value) {
717
738
  const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
718
739
  if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
719
740
  const edit = {};
720
- for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings") problems.push(`there is no field "${key}"`);
741
+ for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "tools") problems.push(`there is no field "${key}"`);
721
742
  for (const key of TEXT_FIELDS) {
722
743
  if (input[key] === void 0) continue;
723
744
  if (typeof input[key] === "string") edit[key] = input[key].trim();
@@ -742,6 +763,11 @@ function parseWorldInfoEdit(value) {
742
763
  edit["alternateOpenings"] = kept;
743
764
  }
744
765
  }
766
+ if (input["tools"] !== void 0) {
767
+ const board = parseSwitchboard(input["tools"], "tools");
768
+ if (typeof board === "string") problems.push(board);
769
+ else edit["tools"] = board;
770
+ }
745
771
  if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
746
772
  if (edit["name"] === "") problems.push("the world needs a name");
747
773
  if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
@@ -772,6 +798,17 @@ function readAlternateOpenings(reader) {
772
798
  }
773
799
  return openings.length === 0 ? void 0 : openings;
774
800
  }
801
+ /** `tools`: switches by kind of agent and tool name; a world carried from a version with other tools still loads. */
802
+ function readTools(reader) {
803
+ const value = reader.raw("tools");
804
+ if (value === void 0) return void 0;
805
+ const board = parseSwitchboard(value, "tools");
806
+ if (typeof board === "string") {
807
+ reader.fail("tools", board.replace(/^"tools"\s*/, ""));
808
+ return;
809
+ }
810
+ return Object.keys(board).length === 0 ? void 0 : board;
811
+ }
775
812
  /** `rules` is one rule as text, or a list of them; blank ones are left out. */
776
813
  function readRules(reader) {
777
814
  const value = reader.raw("rules");
@@ -865,6 +902,7 @@ function parseWorldFile(text) {
865
902
  const clock = readClock(reader);
866
903
  const variables = readVariableValues(reader);
867
904
  const rules = readRules(reader);
905
+ const tools = readTools(reader);
868
906
  const alternateOpenings = readAlternateOpenings(reader);
869
907
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
870
908
  if (name === void 0 || issues.length > 0) return {
@@ -885,6 +923,7 @@ function parseWorldFile(text) {
885
923
  ...clock === void 0 ? {} : { clock },
886
924
  ...variables === void 0 ? {} : { variables },
887
925
  ...rules === void 0 ? {} : { rules },
926
+ ...tools === void 0 ? {} : { tools },
888
927
  ...alternateOpenings === void 0 ? {} : { alternateOpenings },
889
928
  ...narrationVoice === void 0 ? {} : { narrationVoice }
890
929
  }
@@ -1169,6 +1208,8 @@ function readRoutine(reader) {
1169
1208
  if (from !== void 0 && from === to) window.fail("to", "a window that ends when it starts is empty");
1170
1209
  const activity = window.string("activity", { required: true });
1171
1210
  const days = window.strings("days").map((day) => day.toLowerCase());
1211
+ const on = window.strings("on");
1212
+ for (const problem of dayTokenProblems(on, "on", "any")) window.fail("on", problem.replace(/^on: /, ""));
1172
1213
  for (const day of days) if (!WEEKDAY_NAMES.includes(day)) window.fail("days", `"${day}" is not a day (${WEEKDAY_NAMES.join(", ")})`);
1173
1214
  const location = window.string("location");
1174
1215
  const feature = window.string("feature");
@@ -1179,6 +1220,7 @@ function readRoutine(reader) {
1179
1220
  if (from === void 0 || to === void 0 || activity === void 0) return [];
1180
1221
  return [{
1181
1222
  days,
1223
+ ...on.length === 0 ? {} : { on },
1182
1224
  from,
1183
1225
  to,
1184
1226
  activity,
@@ -3667,6 +3709,159 @@ async function loadLore(worldDir) {
3667
3709
  return result;
3668
3710
  }
3669
3711
  //#endregion
3712
+ //#region src/host/calendar/load.ts
3713
+ const CALENDAR_FILE_NAME = "calendar.json";
3714
+ const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
3715
+ /**
3716
+ * 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`,
3717
+ * `09-21..09-22`, `nth:mon:1`, `season:winter`, a month, a weekday); it cannot name another holiday.
3718
+ */
3719
+ function parseCalendarFile(text) {
3720
+ const issues = [];
3721
+ const reader = Reader.fromJson(text, issues);
3722
+ if (reader === void 0) return {
3723
+ ok: false,
3724
+ issues
3725
+ };
3726
+ const hemisphere = reader.oneOf("hemisphere", ["north", "south"], "north");
3727
+ const seen = /* @__PURE__ */ new Set();
3728
+ const holidays = reader.objects("holidays").flatMap((entry) => {
3729
+ const id = entry.string("id", { required: true });
3730
+ const name = entry.string("name", { required: true });
3731
+ const on = entry.strings("on");
3732
+ if (id !== void 0 && !HOLIDAY_ID.test(id)) entry.fail("id", "is made of letters, digits, \"-\" and \"_\" (at most 60)");
3733
+ if (id !== void 0 && seen.has(id)) entry.fail("id", `"${id}" is used by another holiday`);
3734
+ if (id !== void 0) seen.add(id);
3735
+ 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(", ")}`);
3736
+ for (const problem of dayTokenProblems(on, "on")) entry.fail("on", problem.replace(/^on: /, ""));
3737
+ return id === void 0 || name === void 0 ? [] : [{
3738
+ id,
3739
+ name,
3740
+ on
3741
+ }];
3742
+ });
3743
+ if (holidays.length > 60) reader.fail("holidays", `a world has at most 60 holidays`);
3744
+ return issues.length > 0 ? {
3745
+ ok: false,
3746
+ issues
3747
+ } : {
3748
+ ok: true,
3749
+ value: {
3750
+ hemisphere,
3751
+ holidays
3752
+ }
3753
+ };
3754
+ }
3755
+ /** The calendar of a world: an optional `<world>/calendar.json`; a world without one has none. */
3756
+ async function loadCalendar(worldDir) {
3757
+ const result = {
3758
+ calendar: {
3759
+ hemisphere: "north",
3760
+ holidays: []
3761
+ },
3762
+ problems: []
3763
+ };
3764
+ const file = join(worldDir, CALENDAR_FILE_NAME);
3765
+ try {
3766
+ result.calendar = await readDocument(file, parseCalendarFile, result.problems) ?? result.calendar;
3767
+ } catch (error) {
3768
+ if (error.code !== "ENOENT") result.problems.push({
3769
+ path: file,
3770
+ message: errorMessage(error)
3771
+ });
3772
+ }
3773
+ return result;
3774
+ }
3775
+ //#endregion
3776
+ //#region src/host/dice/load.ts
3777
+ const DICE_FILE_NAME = "dice.json";
3778
+ function readBand(band) {
3779
+ const label = band.string("label", { required: true });
3780
+ const result = band.oneOf("result", DICE_RESULTS, "failed");
3781
+ const min = band.number("min");
3782
+ const max = band.number("max");
3783
+ const critical = band.raw("critical");
3784
+ if (critical !== void 0 && critical !== null && typeof critical !== "boolean") band.fail("critical", "must be true or false");
3785
+ if (band.raw("result") === void 0) band.fail("result", `is required: one of ${DICE_RESULTS.join(", ")}`);
3786
+ return label === void 0 ? void 0 : {
3787
+ label,
3788
+ result,
3789
+ ...min === void 0 ? {} : { min },
3790
+ ...max === void 0 ? {} : { max },
3791
+ ...critical === true ? { critical: true } : {}
3792
+ };
3793
+ }
3794
+ /**
3795
+ * 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:
3796
+ * the game master rolls a check and is told the band the roll fell in, never a number to interpret.
3797
+ */
3798
+ function parseDiceFile(text) {
3799
+ const issues = [];
3800
+ const reader = Reader.fromJson(text, issues);
3801
+ if (reader === void 0) return {
3802
+ ok: false,
3803
+ issues
3804
+ };
3805
+ const checks = reader.objects("checks").flatMap((entry) => {
3806
+ const key = entry.string("key", { required: true });
3807
+ const name = entry.string("name", { required: true });
3808
+ const use = entry.string("use", { required: true });
3809
+ const dice = entry.string("dice", { required: true });
3810
+ const reading = entry.oneOf("reading", DICE_READINGS, "total");
3811
+ const compare = entry.oneOf("compare", DICE_COMPARISONS, "absolute");
3812
+ const hit = entry.number("hit", { min: 1 });
3813
+ const modifier = entry.string("modifier");
3814
+ const bands = entry.objects("bands").flatMap((band) => {
3815
+ const read = readBand(band);
3816
+ return read === void 0 ? [] : [read];
3817
+ });
3818
+ if (key === void 0 || name === void 0 || use === void 0 || dice === void 0) return [];
3819
+ const definition = {
3820
+ key,
3821
+ name,
3822
+ use,
3823
+ dice,
3824
+ reading,
3825
+ compare,
3826
+ bands,
3827
+ ...hit === void 0 ? {} : { hit },
3828
+ ...modifier === void 0 || modifier === "" ? {} : { modifier }
3829
+ };
3830
+ for (const problem of checkProblems(definition)) entry.fail("", problem);
3831
+ return [definition];
3832
+ });
3833
+ const seen = /* @__PURE__ */ new Set();
3834
+ for (const check of checks) {
3835
+ if (seen.has(check.key)) reader.fail("checks", `the key "${check.key}" is used by more than one check`);
3836
+ seen.add(check.key);
3837
+ }
3838
+ if (checks.length > 40) reader.fail("checks", `a world has at most 40 checks`);
3839
+ return issues.length > 0 ? {
3840
+ ok: false,
3841
+ issues
3842
+ } : {
3843
+ ok: true,
3844
+ value: checks
3845
+ };
3846
+ }
3847
+ /** The checks of a world: an optional `<world>/dice.json`; a world without one has none, and its game master rolls plain dice only. */
3848
+ async function loadDice(worldDir) {
3849
+ const result = {
3850
+ checks: [],
3851
+ problems: []
3852
+ };
3853
+ const file = join(worldDir, DICE_FILE_NAME);
3854
+ try {
3855
+ result.checks = await readDocument(file, parseDiceFile, result.problems) ?? [];
3856
+ } catch (error) {
3857
+ if (error.code !== "ENOENT") result.problems.push({
3858
+ path: file,
3859
+ message: errorMessage(error)
3860
+ });
3861
+ }
3862
+ return result;
3863
+ }
3864
+ //#endregion
3670
3865
  //#region src/host/triggers/load.ts
3671
3866
  const TRIGGERS_FILE_NAME = "triggers.json";
3672
3867
  /** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
@@ -3826,9 +4021,15 @@ function populateVariables(session, defs, world) {
3826
4021
  give("world", 0, world.values);
3827
4022
  }
3828
4023
  /** 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) {
4024
+ function routineProblems(characters, locations, calendar = {
4025
+ hemisphere: "north",
4026
+ holidays: []
4027
+ }) {
3830
4028
  const byId = new Map(locations.map((location) => [location.id, location]));
4029
+ const holidays = new Set(calendar.holidays.map((holiday) => holiday.id));
3831
4030
  return characters.flatMap((character) => (character.routine ?? []).flatMap((window, index) => {
4031
+ const days = dayTokenProblems(window.on ?? [], `${character.id}: routine[${index}].on`, holidays);
4032
+ if (days.length > 0) return days;
3832
4033
  if (window.location === void 0) return [];
3833
4034
  const location = byId.get(window.location);
3834
4035
  if (location === void 0) return [`${character.id}: routine[${index}].location "${window.location}" is not a place of this world`];
@@ -3836,12 +4037,21 @@ function routineProblems(characters, locations) {
3836
4037
  return [];
3837
4038
  }));
3838
4039
  }
4040
+ /** Keeps the checks of the world with the story: what its game master rolls and how the dice are read. */
4041
+ function populateDice(session, checks) {
4042
+ for (const check of checks) session.dice.define(check);
4043
+ }
4044
+ /** Keeps the world's calendar with the story, for the days a routine or a trigger waits for. */
4045
+ function populateCalendar(session, calendar) {
4046
+ if (calendar.holidays.length > 0 || calendar.hemisphere !== "north") writeCalendar(session.metadata, calendar);
4047
+ }
3839
4048
  /** Gives each character its recurring day, with the places by their ids in the world. */
3840
4049
  function populateRoutines(session, characters) {
3841
4050
  for (const { id, routine } of characters) {
3842
4051
  if (routine === void 0 || routine.length === 0) continue;
3843
4052
  session.routines.replace(session.characters.getBySourceId(id).id, routine.map((window) => ({
3844
4053
  days: window.days.map((day) => WEEKDAY_NAMES.indexOf(day)),
4054
+ on: window.on ?? [],
3845
4055
  start: parseTimeOfDay(window.from),
3846
4056
  end: parseTimeOfDay(window.to),
3847
4057
  activity: window.activity,
@@ -4101,7 +4311,11 @@ async function loadValidatedWorld(world) {
4101
4311
  path: world.directory,
4102
4312
  message
4103
4313
  })));
4104
- const days = routineProblems(characters, locations);
4314
+ const { calendar, problems: calendarProblems } = await loadCalendar(world.directory);
4315
+ if (calendarProblems.length > 0) throw new InvalidWorldError(`the calendar of "${world.summary.name}" has ${calendarProblems.length} problem(s)`, calendarProblems);
4316
+ const dice = await loadDice(world.directory);
4317
+ if (dice.problems.length > 0) throw new InvalidWorldError(`the dice checks of "${world.summary.name}" have ${dice.problems.length} problem(s)`, dice.problems);
4318
+ const days = routineProblems(characters, locations, calendar);
4105
4319
  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
4320
  path: world.directory,
4107
4321
  message
@@ -4170,7 +4384,9 @@ async function loadValidatedWorld(world) {
4170
4384
  authoredLore,
4171
4385
  declared,
4172
4386
  scripted,
4173
- authoredPlots
4387
+ authoredPlots,
4388
+ calendar,
4389
+ checks: dice.checks
4174
4390
  };
4175
4391
  }
4176
4392
  //#endregion
@@ -5051,6 +5267,518 @@ async function finish(ctx, world) {
5051
5267
  return result;
5052
5268
  }
5053
5269
  //#endregion
5270
+ //#region src/host/translate/terms.ts
5271
+ const STOP = /* @__PURE__ */ new Set([
5272
+ "the",
5273
+ "and",
5274
+ "for",
5275
+ "with",
5276
+ "from",
5277
+ "that",
5278
+ "this",
5279
+ "his",
5280
+ "her",
5281
+ "their",
5282
+ "she",
5283
+ "he",
5284
+ "they",
5285
+ "you",
5286
+ "your",
5287
+ "but",
5288
+ "not",
5289
+ "when",
5290
+ "where",
5291
+ "what",
5292
+ "who",
5293
+ "one",
5294
+ "two",
5295
+ "its",
5296
+ "has",
5297
+ "had",
5298
+ "was",
5299
+ "were",
5300
+ "are",
5301
+ "there",
5302
+ "then",
5303
+ "now",
5304
+ "at",
5305
+ "in",
5306
+ "on",
5307
+ "of",
5308
+ "to",
5309
+ "a",
5310
+ "an"
5311
+ ]);
5312
+ const MAX_TERMS = 40;
5313
+ const MIN_USES = 3;
5314
+ const capitalised = (word) => /^\p{Lu}[\p{L}'’-]{2,}$/u.test(word) && !STOP.has(word.toLowerCase());
5315
+ /** The parts of a name written "Place - Room": each part is a name of its own, and so is the whole. */
5316
+ function partsOfName(name) {
5317
+ return name.split(/\s+[-–—]\s+/).map((part) => part.trim()).filter((part) => part !== "");
5318
+ }
5319
+ /**
5320
+ * 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
5321
+ * 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.
5322
+ */
5323
+ function recurringTerms(names, texts) {
5324
+ const known = new Set(names);
5325
+ const found = /* @__PURE__ */ new Map();
5326
+ const add = (term, uses) => {
5327
+ if (!known.has(term)) found.set(term, (found.get(term) ?? 0) + uses);
5328
+ };
5329
+ for (const name of names) for (const part of partsOfName(name)) if (part !== name) add(part, MIN_USES);
5330
+ const counts = /* @__PURE__ */ new Map();
5331
+ for (const text of [...names, ...texts]) {
5332
+ const words = text.split(/[^\p{L}'’-]+/u);
5333
+ for (let at = 0; at < words.length; at += 1) for (const size of [2, 3]) {
5334
+ const phrase = words.slice(at, at + size);
5335
+ if (phrase.length !== size || !phrase.every((word) => capitalised(word.replace(/['’]s$/, "")))) continue;
5336
+ const key = phrase.join(" ").replace(/['’]s$/, "");
5337
+ counts.set(key, (counts.get(key) ?? 0) + 1);
5338
+ }
5339
+ }
5340
+ for (const [phrase, uses] of counts) if (uses >= MIN_USES) add(phrase, uses);
5341
+ return [...found].sort((a, b) => b[1] - a[1]).slice(0, MAX_TERMS).map(([term]) => term);
5342
+ }
5343
+ /** Whether `text` uses `term` as a word of its own (case as written). */
5344
+ function usesTerm(text, term) {
5345
+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5346
+ return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "u").test(text);
5347
+ }
5348
+ //#endregion
5349
+ //#region src/host/translate/prose.ts
5350
+ const rooted = (roots, paths) => roots.flatMap((root) => paths.map((path) => `${root}${path}`));
5351
+ const INTENT = [
5352
+ ".name",
5353
+ ".description",
5354
+ ".plan[]",
5355
+ ".open_threads[]",
5356
+ ".constraints[]"
5357
+ ];
5358
+ const FIELDS = {
5359
+ world: {
5360
+ names: ["name"],
5361
+ text: [
5362
+ "description",
5363
+ "rules[]",
5364
+ "metadata.tags[]",
5365
+ "opening_message",
5366
+ "opening_message[].text",
5367
+ "alternate_openings[].title",
5368
+ "alternate_openings[].text"
5369
+ ]
5370
+ },
5371
+ calendar: {
5372
+ names: ["holidays[].name"],
5373
+ text: []
5374
+ },
5375
+ variables: {
5376
+ names: [],
5377
+ text: rooted(["[]", "variables[]"], [
5378
+ ".name",
5379
+ ".description",
5380
+ ".bands[].label"
5381
+ ])
5382
+ },
5383
+ triggers: {
5384
+ names: [],
5385
+ text: rooted(["[]", "triggers[]"], [
5386
+ ".name",
5387
+ ".announce.text",
5388
+ ".effects[].text",
5389
+ ".effects[].edit.events[].text"
5390
+ ])
5391
+ },
5392
+ plots: {
5393
+ names: [],
5394
+ text: [
5395
+ "plots[].name",
5396
+ "plots[].premise",
5397
+ "plots[].themes[]",
5398
+ "plots[].stakes[]",
5399
+ "plots[].resolutions[]",
5400
+ ...["hooks", "developments"].flatMap((list) => [
5401
+ `plots[].${list}[].text`,
5402
+ `plots[].${list}[].prerequisites[]`,
5403
+ `plots[].${list}[].guidance`,
5404
+ `plots[].${list}[].avoid[]`
5405
+ ])
5406
+ ]
5407
+ },
5408
+ character: {
5409
+ names: ["name", "aliases[]"],
5410
+ text: [
5411
+ "age",
5412
+ "gender",
5413
+ "summary",
5414
+ "personality",
5415
+ "background",
5416
+ "appearance",
5417
+ "speech.style",
5418
+ "speech.examples[]",
5419
+ "start.public_state",
5420
+ "start.inner_state",
5421
+ "start.activity",
5422
+ ...INTENT.map((path) => `start.intents[]${path}`),
5423
+ "relationships[].label",
5424
+ "relationships[].summary",
5425
+ "routine[].activity"
5426
+ ]
5427
+ },
5428
+ location: {
5429
+ names: ["name", "features[].name"],
5430
+ text: [
5431
+ "description",
5432
+ "features[].description",
5433
+ "exits[].description",
5434
+ "exits[].note",
5435
+ "exits[].back_description"
5436
+ ]
5437
+ },
5438
+ item: {
5439
+ names: ["name"],
5440
+ text: ["description", "quality"]
5441
+ },
5442
+ faction: {
5443
+ names: ["name", "aliases[]"],
5444
+ text: [
5445
+ "summary",
5446
+ "description",
5447
+ "values[]",
5448
+ "structure",
5449
+ "start.public_state",
5450
+ "start.inner_state",
5451
+ ...INTENT.map((path) => `start.goals[]${path}`),
5452
+ "members[].role",
5453
+ "members[].rank",
5454
+ "relationships[].label",
5455
+ "relationships[].summary"
5456
+ ]
5457
+ },
5458
+ lore: {
5459
+ names: [],
5460
+ text: [
5461
+ "title",
5462
+ "summary",
5463
+ "body"
5464
+ ]
5465
+ }
5466
+ };
5467
+ /** 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. */
5468
+ function leavesOf(kind, document) {
5469
+ const fields = FIELDS[kind];
5470
+ const names = new Set(fields.names);
5471
+ const text = new Set(fields.text);
5472
+ const leaves = [];
5473
+ const visit = (value, pattern, path) => {
5474
+ if (typeof value === "string") {
5475
+ const name = names.has(pattern);
5476
+ if ((name || text.has(pattern)) && /\p{L}/u.test(value)) leaves.push({
5477
+ path,
5478
+ text: value,
5479
+ name
5480
+ });
5481
+ } else if (Array.isArray(value)) value.forEach((entry, index) => {
5482
+ visit(entry, `${pattern}[]`, [...path, index]);
5483
+ });
5484
+ else if (typeof value === "object" && value !== null) for (const [key, entry] of Object.entries(value)) visit(entry, pattern === "" ? key : `${pattern}.${key}`, [...path, key]);
5485
+ };
5486
+ visit(document, "", []);
5487
+ return leaves;
5488
+ }
5489
+ /** Puts `text` where `path` points in the document. */
5490
+ function setLeaf(document, path, text) {
5491
+ let at = document;
5492
+ for (const step of path.slice(0, -1)) at = at[step];
5493
+ at[path[path.length - 1]] = text;
5494
+ }
5495
+ const ROOT_FILES = [
5496
+ ["world.json", "world"],
5497
+ ["calendar.json", "calendar"],
5498
+ ["variables.json", "variables"],
5499
+ ["triggers.json", "triggers"],
5500
+ ["plots.json", "plots"]
5501
+ ];
5502
+ const ENTITIES = [
5503
+ [
5504
+ "characters",
5505
+ "character.json",
5506
+ "character"
5507
+ ],
5508
+ [
5509
+ "locations",
5510
+ "location.json",
5511
+ "location"
5512
+ ],
5513
+ [
5514
+ "items",
5515
+ "item.json",
5516
+ "item"
5517
+ ],
5518
+ [
5519
+ "factions",
5520
+ "faction.json",
5521
+ "faction"
5522
+ ],
5523
+ [
5524
+ "lore",
5525
+ "lore.json",
5526
+ "lore"
5527
+ ]
5528
+ ];
5529
+ async function readIfThere(file) {
5530
+ try {
5531
+ return JSON.parse(await readFile(file, "utf8"));
5532
+ } catch (error) {
5533
+ if (error.code === "ENOENT") return void 0;
5534
+ throw new Error(`${file} cannot be read: ${error instanceof Error ? error.message : String(error)}`);
5535
+ }
5536
+ }
5537
+ /** 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. */
5538
+ async function readWorldDocuments(directory) {
5539
+ const found = [];
5540
+ for (const [file, kind] of ROOT_FILES) {
5541
+ const document = await readIfThere(join(directory, file));
5542
+ if (document !== void 0) found.push({
5543
+ file,
5544
+ kind,
5545
+ document
5546
+ });
5547
+ }
5548
+ for (const [folder, name, kind] of ENTITIES) {
5549
+ let entries;
5550
+ try {
5551
+ entries = (await readdir(join(directory, folder), { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
5552
+ } catch (error) {
5553
+ if (error.code === "ENOENT") continue;
5554
+ throw error;
5555
+ }
5556
+ for (const entry of entries) {
5557
+ const file = join(folder, entry, name);
5558
+ const document = await readIfThere(join(directory, file));
5559
+ if (document !== void 0) found.push({
5560
+ file,
5561
+ kind,
5562
+ document
5563
+ });
5564
+ }
5565
+ }
5566
+ return found;
5567
+ }
5568
+ //#endregion
5569
+ //#region src/host/translate/translate-world.ts
5570
+ /** What is not carried over to a translation: the removed things of the editor and the card import's working files. */
5571
+ const NOT_COPIED = /* @__PURE__ */ new Set([".trash", ".import"]);
5572
+ const TERMS_PER_JOB = 40;
5573
+ const TEXTS_PER_JOB = 30;
5574
+ const CHARS_PER_JOB = 5e3;
5575
+ const GLOSSARY_SHOWN = 60;
5576
+ /** A text with fewer letters than this is too short to check which language it came out in. */
5577
+ const CHECKED_LETTERS = 40;
5578
+ /** A name shorter than this is too likely to be an ordinary word to be held to the glossary. */
5579
+ const MIN_TERM = 4;
5580
+ var TranslationRefusedError = class extends Error {};
5581
+ const STRINGS = {
5582
+ type: "array",
5583
+ items: { type: "string" }
5584
+ };
5585
+ const GLOSSARY_SCHEMA = {
5586
+ type: "object",
5587
+ properties: { terms: {
5588
+ type: "array",
5589
+ items: {
5590
+ type: "object",
5591
+ properties: {
5592
+ source: { type: "string" },
5593
+ target: { type: "string" }
5594
+ },
5595
+ required: ["source", "target"],
5596
+ additionalProperties: false
5597
+ },
5598
+ description: "One entry for each name given, in the same order, with the source exactly as given."
5599
+ } },
5600
+ required: ["terms"],
5601
+ additionalProperties: false
5602
+ };
5603
+ const TEXTS_SCHEMA = {
5604
+ type: "object",
5605
+ properties: { translations: {
5606
+ ...STRINGS,
5607
+ description: "The translation of each text, in the order given."
5608
+ } },
5609
+ required: ["translations"],
5610
+ additionalProperties: false
5611
+ };
5612
+ const braces = (text) => (text.match(/\{[^{}]*\}/g) ?? []).sort().join("\0");
5613
+ const letters = (text) => text.match(/\p{L}/gu)?.length ?? 0;
5614
+ /** The language the world is written in, from the words of all its files; nothing when there are too few to tell. */
5615
+ function languageOfDocuments(documents) {
5616
+ return textLanguage(documents.flatMap((entry) => leavesOf(entry.kind, entry.document).map((leaf) => leaf.text)).join("\n"));
5617
+ }
5618
+ function batches(items, size, maxItems, maxSize) {
5619
+ const out = [];
5620
+ let current = [];
5621
+ let used = 0;
5622
+ for (const item of items) {
5623
+ if (current.length > 0 && (current.length >= maxItems || used + size(item) > maxSize)) {
5624
+ out.push(current);
5625
+ current = [];
5626
+ used = 0;
5627
+ }
5628
+ current.push(item);
5629
+ used += size(item);
5630
+ }
5631
+ if (current.length > 0) out.push(current);
5632
+ return out;
5633
+ }
5634
+ /** Why a set of translations cannot be used, or nothing. A text left in the language it was written in is not a translation. */
5635
+ function problemWith(sources, from, translations, glossary) {
5636
+ if (translations.length !== sources.length) return `${sources.length} texts were given and ${translations.length} translations came back: give exactly one for each, in order`;
5637
+ for (const [index, source] of sources.entries()) {
5638
+ const text = translations[index];
5639
+ if (text.trim() === "") return `translation ${index + 1} is empty`;
5640
+ if (braces(source) !== braces(text)) return `translation ${index + 1} must keep the text in curly braces exactly as it is: ${(source.match(/\{[^{}]*\}/g) ?? []).join(" ")}`;
5641
+ if (letters(source) >= CHECKED_LETTERS && textLanguage(source) === from && textLanguage(text) === from) return `translation ${index + 1} is still in the original language`;
5642
+ 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}"`;
5643
+ }
5644
+ }
5645
+ async function glossaryOf(ctx, names, vars, known = /* @__PURE__ */ new Map()) {
5646
+ const jobs = batches(names, () => 1, TERMS_PER_JOB, TERMS_PER_JOB);
5647
+ const parts = await mapLimit(jobs, ctx.concurrency, async (terms) => {
5648
+ const job = {
5649
+ persona: ctx.text("translate/glossary", vars),
5650
+ prompt: JSON.stringify({
5651
+ known: Object.fromEntries([...known].filter(([source]) => terms.some((term) => term.toLowerCase().includes(source.toLowerCase())))),
5652
+ names: terms
5653
+ }),
5654
+ result: GLOSSARY_SCHEMA,
5655
+ check: (value) => {
5656
+ if (value.terms.length !== terms.length) return `${terms.length} names were given and ${value.terms.length} came back: one for each, in order`;
5657
+ const wrong = terms.findIndex((term, index) => value.terms[index].source !== term || value.terms[index].target.trim() === "");
5658
+ return wrong === -1 ? void 0 : `entry ${wrong + 1} must repeat "${terms[wrong]}" exactly and have a translation`;
5659
+ }
5660
+ };
5661
+ return (await ctx.run(job)).terms;
5662
+ });
5663
+ return new Map(parts.flat().map((term) => [term.source, term.target.trim()]));
5664
+ }
5665
+ async function translated(ctx, texts, glossary, from, vars) {
5666
+ return (await mapLimit(batches(texts, (text) => text.length, TEXTS_PER_JOB, CHARS_PER_JOB), ctx.concurrency, async (group) => {
5667
+ const haystack = group.join("\n").toLowerCase();
5668
+ const shown = [...glossary].filter(([source]) => haystack.includes(source.toLowerCase())).slice(0, GLOSSARY_SHOWN);
5669
+ const relevant = new Map(shown);
5670
+ const job = {
5671
+ persona: ctx.text("translate/document", vars),
5672
+ prompt: JSON.stringify({
5673
+ glossary: Object.fromEntries(shown),
5674
+ texts: group.map((text, index) => ({
5675
+ n: index + 1,
5676
+ text
5677
+ }))
5678
+ }),
5679
+ result: TEXTS_SCHEMA,
5680
+ check: (value) => problemWith(group, from, value.translations, relevant)
5681
+ };
5682
+ return (await ctx.run(job)).translations;
5683
+ })).flat();
5684
+ }
5685
+ async function freeFolder(directory, suffix) {
5686
+ for (let n = 1;; n += 1) {
5687
+ const candidate = join(dirname(directory), `${basename(directory)} ${suffix}${n === 1 ? "" : ` ${n}`}`);
5688
+ try {
5689
+ await stat(candidate);
5690
+ } catch (error) {
5691
+ if (error.code === "ENOENT") return candidate;
5692
+ throw error;
5693
+ }
5694
+ }
5695
+ }
5696
+ async function listedIn(directory, names) {
5697
+ const present = new Set(await readdir(directory));
5698
+ return names.filter((name) => present.has(name));
5699
+ }
5700
+ /**
5701
+ * 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.
5702
+ * The original is never changed. The copy gets an id of its own and is checked as a story start would check it.
5703
+ */
5704
+ async function translateWorld(ctx, worlds, source, to, told) {
5705
+ const documents = await readWorldDocuments(source.directory);
5706
+ const from = languageOfDocuments(documents);
5707
+ if (from === void 0) throw new TranslationRefusedError("there is too little text in this world to tell which language it is written in");
5708
+ if (from === to) throw new TranslationRefusedError(`this world is already written in ${LANGUAGE_NAMES[to].en}`);
5709
+ const vars = {
5710
+ from: LANGUAGE_NAMES[from][told],
5711
+ to: LANGUAGE_NAMES[to][told]
5712
+ };
5713
+ const leaves = documents.map((entry) => ({
5714
+ entry,
5715
+ leaves: leavesOf(entry.kind, entry.document)
5716
+ }));
5717
+ const names = [...new Set(leaves.flatMap((item) => item.leaves.filter((leaf) => leaf.name).map((leaf) => leaf.text)))];
5718
+ ctx.say(`translating ${names.length} names`);
5719
+ const prose = leaves.flatMap((item) => item.leaves.filter((leaf) => !leaf.name).map((leaf) => leaf.text));
5720
+ const recurring = from === "en" ? recurringTerms(names, prose) : [];
5721
+ const parts = await glossaryOf(ctx, recurring, vars);
5722
+ const glossary = await glossaryOf(ctx, names, vars, parts);
5723
+ for (const [term, rendering] of parts) glossary.set(term, rendering);
5724
+ let texts = 0;
5725
+ for (const { entry, leaves: own } of leaves) {
5726
+ const words = own.filter((leaf) => !leaf.name);
5727
+ for (const leaf of own.filter((item) => item.name)) setLeaf(entry.document, leaf.path, glossary.get(leaf.text) ?? leaf.text);
5728
+ if (words.length === 0) continue;
5729
+ ctx.say(`translating ${entry.file}`);
5730
+ const result = await translated(ctx, words.map((leaf) => leaf.text), glossary, from, vars);
5731
+ for (const [index, leaf] of words.entries()) setLeaf(entry.document, leaf.path, result[index]);
5732
+ texts += words.length;
5733
+ }
5734
+ for (const { entry, leaves: own } of leaves) {
5735
+ const document = entry.document;
5736
+ if (entry.kind !== "character" && entry.kind !== "faction") continue;
5737
+ const original = own.find((leaf) => leaf.name && leaf.path.length === 1 && leaf.path[0] === "name")?.text;
5738
+ const aliases = Array.isArray(document["aliases"]) ? document["aliases"] : [];
5739
+ if (original !== void 0 && original !== document["name"] && !aliases.includes(original)) document["aliases"] = [...aliases, original];
5740
+ }
5741
+ const id = randomUUID();
5742
+ const destination = await freeFolder(source.directory, to);
5743
+ await cp(source.directory, destination, {
5744
+ recursive: true,
5745
+ filter: (path) => !NOT_COPIED.has(relative(source.directory, path).split(sep)[0])
5746
+ });
5747
+ for (const entry of documents) {
5748
+ const document = entry.kind === "world" ? (({ id: _old, ...rest }) => ({
5749
+ id,
5750
+ ...rest
5751
+ }))(entry.document) : entry.document;
5752
+ await writeFile(join(destination, entry.file), `${JSON.stringify(document, null, 2)}\n`);
5753
+ }
5754
+ const payload = await worlds.list({ refresh: true });
5755
+ const made = payload.worlds.find((world) => world.id === id);
5756
+ 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("; ")}`);
5757
+ const record = await worlds.find(id);
5758
+ const problems = [];
5759
+ if (record !== void 0) try {
5760
+ await loadValidatedWorld(record);
5761
+ } catch (error) {
5762
+ if (!(error instanceof InvalidWorldError)) throw error;
5763
+ problems.push(...error.problems.map((problem) => `${relative(destination, problem.path) || "."}: ${problem.message}`));
5764
+ }
5765
+ return {
5766
+ worldId: id,
5767
+ name: made.name,
5768
+ folder: basename(destination),
5769
+ documents: documents.length,
5770
+ texts,
5771
+ names: names.length + recurring.length,
5772
+ problems,
5773
+ copiedAsIs: await listedIn(source.directory, [
5774
+ "prompts",
5775
+ "ui",
5776
+ "images",
5777
+ "media"
5778
+ ])
5779
+ };
5780
+ }
5781
+ //#endregion
5054
5782
  //#region src/shared/authoring-chat.ts
5055
5783
  const PREFIX = "world-author-";
5056
5784
  /** Stable DSH chat identity for the authoring conversation of one world. */
@@ -5069,6 +5797,249 @@ function authoredWorldOf(chatSessionId) {
5069
5797
  }
5070
5798
  }
5071
5799
  //#endregion
5800
+ //#region src/host/import/tools.ts
5801
+ const SURVEY_TOOL = "import_survey";
5802
+ const BUILD_TOOL = "import_build";
5803
+ const FINISH_TOOL = "import_finish";
5804
+ /** How many times a turn that has not finished the import is sent back to it. */
5805
+ const MAX_OBJECTIONS = 3;
5806
+ /** A model call that fails is made once more before the piece it was for is given up. */
5807
+ const ATTEMPTS = 2;
5808
+ const CARD = `${IMPORT_FOLDER}/card.json`;
5809
+ const cardParameter = {
5810
+ type: "string",
5811
+ required: true,
5812
+ description: `The card to import: the path that follows /import-st in the person's message (${CARD}).`
5813
+ };
5814
+ /** 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. */
5815
+ function checkedCard(args) {
5816
+ if (args.card.trim() !== CARD) throw new Error(`the card to import is ${CARD}`);
5817
+ }
5818
+ const output = (render) => ({
5819
+ schema: { type: "json" },
5820
+ render: (_args, value) => [{
5821
+ type: "text",
5822
+ text: render(value)
5823
+ }]
5824
+ });
5825
+ const json = (value) => JSON.parse(JSON.stringify(value));
5826
+ /** The runner of an import: every job is a narrow agent below the chat's own, on the chat's model. */
5827
+ function contextOf(exec, settings, text) {
5828
+ const agent = exec.agent;
5829
+ if (agent === void 0) throw new Error("the import tools can only be called by an agent");
5830
+ const run = async (job) => {
5831
+ for (let attempt = 1;; attempt += 1) try {
5832
+ return await runChild({
5833
+ parent: agent,
5834
+ signal: exec.signal,
5835
+ persona: job.persona,
5836
+ prompt: job.prompt,
5837
+ result: job.result,
5838
+ ...job.check === void 0 ? {} : { beforeSubmit: (value) => job.check?.(value) },
5839
+ maxTokens: settings.maxTokens,
5840
+ sampling: {
5841
+ temperature: settings.temperature,
5842
+ toolChoice: "required"
5843
+ },
5844
+ ...settings.reasoning === "" ? {} : { reasoningEffort: settings.reasoning }
5845
+ });
5846
+ } catch (error) {
5847
+ if (exec.signal.aborted || attempt >= ATTEMPTS) throw error;
5848
+ }
5849
+ };
5850
+ return {
5851
+ run,
5852
+ concurrency: settings.concurrency,
5853
+ text,
5854
+ say: () => void 0
5855
+ };
5856
+ }
5857
+ async function worldOf(worlds, exec) {
5858
+ const chat = exec.agent?.session.id;
5859
+ const worldId = chat === void 0 ? void 0 : authoredWorldOf(chat);
5860
+ if (worldId === void 0) throw new Error("the import tools are available only in a world authoring chat");
5861
+ const record = await worlds.find(worldId);
5862
+ if (record === void 0) throw new Error(`the authored world "${worldId}" no longer exists`);
5863
+ return {
5864
+ id: worldId,
5865
+ directory: record.directory
5866
+ };
5867
+ }
5868
+ const toolNames = {
5869
+ survey: SURVEY_TOOL,
5870
+ build: BUILD_TOOL,
5871
+ finish: FINISH_TOOL
5872
+ };
5873
+ /** 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. */
5874
+ function importTools(worlds, settings, prompting) {
5875
+ /** 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. */
5876
+ const step = async (exec, work, next) => {
5877
+ const world = await worldOf(worlds, exec);
5878
+ const language = prompting.languages().get(world.id);
5879
+ const text = (id, variables) => prompting.prompts().text(id, language, {
5880
+ ...toolNames,
5881
+ ...variables
5882
+ });
5883
+ const result = await work(contextOf(exec, settings(), text), world.directory);
5884
+ return json({
5885
+ ...result,
5886
+ next: next(text, result)
5887
+ });
5888
+ };
5889
+ return [
5890
+ defineTool({
5891
+ name: SURVEY_TOOL,
5892
+ 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.",
5893
+ parameters: { card: cardParameter },
5894
+ output: output((value) => JSON.stringify(value, null, 1)),
5895
+ isConcurrencySafe: () => false,
5896
+ async execute(args, exec) {
5897
+ checkedCard(args);
5898
+ return await step(exec, survey, (text) => text("import/next-survey"));
5899
+ }
5900
+ }),
5901
+ defineTool({
5902
+ name: BUILD_TOOL,
5903
+ 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.",
5904
+ parameters: { card: cardParameter },
5905
+ output: output((value) => JSON.stringify(value, null, 1)),
5906
+ isConcurrencySafe: () => false,
5907
+ async execute(args, exec) {
5908
+ checkedCard(args);
5909
+ return await step(exec, build, (text) => text("import/next-build"));
5910
+ }
5911
+ }),
5912
+ defineTool({
5913
+ name: FINISH_TOOL,
5914
+ 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.",
5915
+ parameters: { card: cardParameter },
5916
+ output: output((value) => JSON.stringify(value, null, 1)),
5917
+ isConcurrencySafe: () => false,
5918
+ async execute(args, exec) {
5919
+ checkedCard(args);
5920
+ return await step(exec, finish, (text, result) => text(result.ok ? "import/finish-ok" : "import/finish-failed"));
5921
+ }
5922
+ })
5923
+ ];
5924
+ }
5925
+ /** The procedure of an import turn, told to the chat in place of what it does for any other message. */
5926
+ function importNotice(phase, text) {
5927
+ if (phase === void 0) return text("import/notice-missing");
5928
+ return text("import/notice", {
5929
+ card: CARD,
5930
+ phase,
5931
+ done: phase === "done" ? text("import/notice-done") : ""
5932
+ });
5933
+ }
5934
+ /** 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. */
5935
+ function importHooks(ctx, worlds, prompting) {
5936
+ const textFor = (worldId) => (id, variables) => prompting.prompts().text(id, worldId === void 0 ? void 0 : prompting.languages().get(worldId), {
5937
+ ...toolNames,
5938
+ ...variables
5939
+ });
5940
+ const imports = /* @__PURE__ */ new Map();
5941
+ const objections = /* @__PURE__ */ new Map();
5942
+ const authoring = (agent) => agent.session.header.origin === "subagent" || authoredWorldOf(agent.session.id) === void 0 ? void 0 : agent.session.id;
5943
+ ctx.on("agent/pre-step", async (payload, next) => {
5944
+ const decision = await next();
5945
+ const chat = authoring(payload.agent);
5946
+ if (decision.kind !== "enter" || payload.step !== 1 || chat === void 0) return decision;
5947
+ 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;
5948
+ const worldId = authoredWorldOf(chat);
5949
+ const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
5950
+ const phase = record === void 0 ? void 0 : await importPhase(record.directory);
5951
+ if (phase !== void 0 && phase !== "done") {
5952
+ imports.set(chat, payload.turn);
5953
+ objections.delete(chat);
5954
+ }
5955
+ return {
5956
+ ...decision,
5957
+ messages: [...decision.messages, createUserMessage({
5958
+ content: [{
5959
+ type: "text",
5960
+ text: importNotice(phase, textFor(worldId))
5961
+ }],
5962
+ source: { kind: "roleplay" }
5963
+ })]
5964
+ };
5965
+ });
5966
+ ctx.on("session/event", async (session, event) => {
5967
+ if (event.type !== "turn/end" || session.header.origin === "subagent") return;
5968
+ const worldId = authoredWorldOf(session.id);
5969
+ const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
5970
+ if (record !== void 0) await endReview(record.directory);
5971
+ });
5972
+ ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
5973
+ const chat = authoring(agent);
5974
+ if (chat === void 0 || imports.get(chat) !== turn) return;
5975
+ const worldId = authoredWorldOf(chat);
5976
+ const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
5977
+ const phase = record === void 0 ? void 0 : await importPhase(record.directory);
5978
+ if (phase === void 0 || phase === "done") {
5979
+ imports.delete(chat);
5980
+ return;
5981
+ }
5982
+ const told = objections.get(chat) ?? 0;
5983
+ if (told >= MAX_OBJECTIONS) {
5984
+ imports.delete(chat);
5985
+ return;
5986
+ }
5987
+ objections.set(chat, told + 1);
5988
+ const next = phase === "ready" ? SURVEY_TOOL : phase === "surveyed" ? BUILD_TOOL : FINISH_TOOL;
5989
+ agent.steer(createUserMessage({
5990
+ content: [{
5991
+ type: "text",
5992
+ text: textFor(worldId)("import/steer", {
5993
+ phase,
5994
+ next,
5995
+ card: CARD
5996
+ })
5997
+ }],
5998
+ source: { kind: "roleplay" }
5999
+ }));
6000
+ });
6001
+ }
6002
+ //#endregion
6003
+ //#region src/host/translate/tools.ts
6004
+ const TRANSLATE_TOOL = "translate_world";
6005
+ /** The message that has the authoring chat translate its world, in the language of the person who asked. */
6006
+ function translateMessage(text, to, language) {
6007
+ return text("translate/notice", {
6008
+ tool: TRANSLATE_TOOL,
6009
+ code: to,
6010
+ to: to === "zh" ? language === "zh" ? "中文" : "Chinese" : language === "zh" ? "英文" : "English"
6011
+ });
6012
+ }
6013
+ /** The tool of the authoring chat that translates the chat's world into a copy in another language. */
6014
+ function translateTools(worlds, settings, prompting) {
6015
+ return [defineTool({
6016
+ name: TRANSLATE_TOOL,
6017
+ 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.",
6018
+ parameters: { language: {
6019
+ type: "string",
6020
+ required: true,
6021
+ enum: [...STORY_LANGUAGES],
6022
+ description: "The language to translate into: en or zh."
6023
+ } },
6024
+ output: {
6025
+ schema: { type: "json" },
6026
+ render: (_args, value) => [{
6027
+ type: "text",
6028
+ text: JSON.stringify(value, null, 1)
6029
+ }]
6030
+ },
6031
+ isConcurrencySafe: () => false,
6032
+ async execute(args, exec) {
6033
+ if (!isStoryLanguage(args.language)) throw new Error(`language must be one of: ${STORY_LANGUAGES.join(", ")}`);
6034
+ const world = await worldOf(worlds, exec);
6035
+ const told = prompting.languages().get(world.id);
6036
+ const text = (id, variables) => prompting.prompts().text(id, told, variables);
6037
+ const report = await translateWorld(contextOf(exec, settings(), text), worlds, world, args.language, told.startsWith("zh") ? "zh" : "en");
6038
+ return JSON.parse(JSON.stringify(report));
6039
+ }
6040
+ })];
6041
+ }
6042
+ //#endregion
5072
6043
  //#region src/host/triggers/parts.ts
5073
6044
  /** 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. */
5074
6045
  async function loadWorldParts(directory) {
@@ -5079,11 +6050,13 @@ async function loadWorldParts(directory) {
5079
6050
  locations
5080
6051
  });
5081
6052
  const { defs, problems: variableProblems } = await loadVariables(directory);
6053
+ const { calendar, problems: calendarProblems } = await loadCalendar(directory);
5082
6054
  const problems = [
5083
6055
  ...characterProblems,
5084
6056
  ...locationProblems,
5085
6057
  ...itemProblems,
5086
- ...variableProblems
6058
+ ...variableProblems,
6059
+ ...calendarProblems
5087
6060
  ];
5088
6061
  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("; ")}`]);
5089
6062
  return {
@@ -5091,7 +6064,8 @@ async function loadWorldParts(directory) {
5091
6064
  locations,
5092
6065
  items,
5093
6066
  slots,
5094
- variables: defs
6067
+ variables: defs,
6068
+ calendar
5095
6069
  };
5096
6070
  }
5097
6071
  //#endregion
@@ -5114,6 +6088,7 @@ function triggerProblemsOf(parts, definitions) {
5114
6088
  }, { vectors: false });
5115
6089
  try {
5116
6090
  const session = scratch;
6091
+ if (parts.calendar !== void 0) writeCalendar(scratch.metadata, parts.calendar);
5117
6092
  populateLocations(session, parts.locations);
5118
6093
  populateCharacters(session, parts.characters, parts.characters.find((character) => character.role === "playable")?.id ?? "");
5119
6094
  populateItems(session, parts.items, parts.slots, parts.locations);
@@ -5222,12 +6197,15 @@ async function readWorldEditor(world) {
5222
6197
  locations
5223
6198
  });
5224
6199
  const scripted = await loadTriggers(world.directory);
6200
+ const declared = await loadVariables(world.directory);
6201
+ const { calendar } = await loadCalendar(world.directory);
5225
6202
  const { triggers, triggersProblem } = triggersOf({
5226
6203
  characters,
5227
6204
  locations,
5228
6205
  items,
5229
6206
  slots,
5230
- variables: (await loadVariables(world.directory)).defs
6207
+ variables: declared.defs,
6208
+ calendar
5231
6209
  }, scripted);
5232
6210
  const names = new Map(locations.map((location) => [location.id, location.name]));
5233
6211
  const characterNames = new Map(characters.map((character) => [character.id, character.name]));
@@ -6026,6 +7004,6 @@ async function deleteAuthoredEntity(world, kind, key) {
6026
7004
  return destination;
6027
7005
  }
6028
7006
  //#endregion
6029
- export { writeWorldPrompt as $, survey as A, populateTriggers as B, authoringChatSessionId as C, importPhase as D, finish as E, populateItems as F, loadItems as G, routineProblems as H, populateKnowledge as I, subfolders as J, CHARACTERS_DIR as K, populateLocations as L, populateCharacters as M, populateClock as N, isReviewing as O, populateFactions as P, readWorldPrompt as Q, populateLore as R, authoredWorldOf as S, endReview as T, TRIGGERS_FILE_NAME as U, populateVariables as V, loadLocations as W, deleteWorldPrompt as X, PROSE_PROMPTS as Y, listWorldPrompts as Z, replaceFile$1 as _, parseRelationEdit as _t, replaceAuthoredEntity as a, IMPORT_FOLDER as at, triggerProblemsOf as b, parseImportCommand as bt, editWorldLore as c, parseChoices as ct, editWorldPlots as d, parseWorldInfoEdit as dt, VARIABLES_FILE_NAME as et, editWorldRelation as f, InvalidEditProblems as ft, readWorldEditor as g, parsePlaceEdit as gt, generateWorldCharacterPortrait as h, parseLoreEdit as ht, readAuthoredEntityDocument as i, parseCharacterFile as it, loadValidatedWorld as j, markReady as k, editWorldNarrationVoice as l, WORLD_FILE_NAME as lt, entityFolder as m, parseFactionEdit as mt, createAuthoredEntity as n, variableProblems as nt, editWorldCharacter as o, ImportNotFoundError as ot, editWorldThing as p, parseCharacterEdit as pt, loadCharacters as q, deleteAuthoredEntity as r, CHARACTER_FILE_NAME as rt, editWorldFaction as s, ImportStore as st, AUTHORED_ENTITY_KINDS as t, parseVariablesFile as tt, editWorldPlace as u, parseWorldFile as ut, uploadWorldCharacterPortrait as v, parseThingEdit as vt, build as w, loadWorldParts as x, worldCharacterPortraitFile as y, IMPORT_COMMAND as yt, populateRoutines as z };
7007
+ export { loadLocations as $, isReviewing as A, DICE_COMPARISONS as At, populateLocations as B, translateTools as C, parseCharacterEdit as Ct, authoringChatSessionId as D, parseRelationEdit as Dt, authoredWorldOf as E, parsePlaceEdit as Et, populateClock as F, routineProblems as G, populateRoutines as H, populateDice as I, loadDice as J, TRIGGERS_FILE_NAME as K, populateFactions as L, loadValidatedWorld as M, DICE_RESULTS as Mt, populateCalendar as N, languageOfDocuments as O, parseThingEdit as Ot, populateCharacters as P, parseCalendarFile as Q, populateItems as R, translateMessage as S, InvalidEditProblems as St, importTools as T, parseLoreEdit as Tt, populateTriggers as U, populateLore as V, populateVariables as W, CALENDAR_FILE_NAME as X, parseDiceFile as Y, loadCalendar as Z, replaceFile$1 as _, ImportStore as _t, replaceAuthoredEntity as a, deleteWorldPrompt as at, triggerProblemsOf as b, parseWorldFile as bt, editWorldLore as c, writeWorldPrompt as ct, editWorldPlots as d, parseVariablesFile as dt, loadItems as et, editWorldRelation as f, variableProblems as ft, readWorldEditor as g, ImportNotFoundError as gt, generateWorldCharacterPortrait as h, IMPORT_FOLDER as ht, readAuthoredEntityDocument as i, PROSE_PROMPTS as it, markReady as j, DICE_READINGS as jt, readWorldDocuments as k, IMPORT_COMMAND as kt, editWorldNarrationVoice as l, VARIABLES_FILE_NAME as lt, entityFolder as m, parseCharacterFile as mt, createAuthoredEntity as n, loadCharacters as nt, editWorldCharacter as o, listWorldPrompts as ot, editWorldThing as p, CHARACTER_FILE_NAME as pt, DICE_FILE_NAME as q, deleteAuthoredEntity as r, subfolders as rt, editWorldFaction as s, readWorldPrompt as st, AUTHORED_ENTITY_KINDS as t, CHARACTERS_DIR as tt, editWorldPlace as u, loadVariables as ut, uploadWorldCharacterPortrait as v, parseChoices as vt, importHooks as w, parseFactionEdit as wt, loadWorldParts as x, parseWorldInfoEdit as xt, worldCharacterPortraitFile as y, WORLD_FILE_NAME as yt, populateKnowledge as z };
6030
7008
 
6031
- //# sourceMappingURL=documents-7GMc5NnW.js.map
7009
+ //# sourceMappingURL=documents-B5XAdfo2.js.map