@dsh-agentic-roleplay/core 0.3.0 → 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 (36) hide show
  1. package/lib/authoring.js +18 -223
  2. package/lib/client.js +903 -478
  3. package/lib/client.js.map +1 -1
  4. package/lib/compaction.js +1 -1
  5. package/lib/{deliver--uMhC6oO.js → deliver-BDW5WZvc.js} +579 -195
  6. package/lib/{documents-7GMc5NnW.js → documents-DtlY2IRt.js} +857 -12
  7. package/lib/{gallery-DUeBMHQX.js → gallery-DACG5eh2.js} +2 -2
  8. package/lib/{generator-HPifO3Kk.js → generator-DGYcLMp7.js} +2 -2
  9. package/lib/images.js +3 -3
  10. package/lib/index.js +181 -11
  11. package/lib/{narration-CKZTk5UE.js → narration-5ig7Dg28.js} +3 -2
  12. package/lib/orchestration.js +366 -274
  13. package/lib/{packs-alJTiDM2.js → packs-CkRZDCsV.js} +49 -5
  14. package/lib/{presenter-agent-PX1WVaJB.js → presenter-agent-PK9JYExk.js} +3 -3
  15. package/package.json +4 -4
  16. package/packs/scene/strip.js +1 -1
  17. package/prompts/en/roleplay/character-decide.md +1 -1
  18. package/prompts/en/roleplay/character-rules.md +1 -1
  19. package/prompts/en/roleplay/chronicler.md +1 -1
  20. package/prompts/en/roleplay/game-master.md +1 -1
  21. package/prompts/en/roleplay/reflection.md +2 -2
  22. package/prompts/en/roleplay/style.md +1 -1
  23. package/prompts/en/roleplay/suggester.md +1 -1
  24. package/prompts/en/translate/document.md +6 -0
  25. package/prompts/en/translate/glossary.md +5 -0
  26. package/prompts/en/translate/notice.md +2 -0
  27. package/prompts/zh/roleplay/character-decide.md +1 -1
  28. package/prompts/zh/roleplay/character-rules.md +1 -1
  29. package/prompts/zh/roleplay/chronicler.md +1 -1
  30. package/prompts/zh/roleplay/game-master.md +1 -1
  31. package/prompts/zh/roleplay/reflection.md +2 -2
  32. package/prompts/zh/roleplay/style.md +1 -1
  33. package/prompts/zh/roleplay/suggester.md +1 -1
  34. package/prompts/zh/translate/document.md +6 -0
  35. package/prompts/zh/translate/glossary.md +5 -0
  36. package/prompts/zh/translate/notice.md +2 -0
@@ -1,4 +1,4 @@
1
- import { S as mapLimit, _ as readImageFileMetadata, c as LIBRARY_FOLDER, g as mediaTypeOf, v as sidecarOf, y as writeImageFileMetadata } from "./generator-HPifO3Kk.js";
1
+ import { S as mapLimit, _ as readImageFileMetadata, c as LIBRARY_FOLDER, g as mediaTypeOf, v as sidecarOf, y as writeImageFileMetadata } from "./generator-DGYcLMp7.js";
2
2
  import { join, sep } from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { lstat, mkdir, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
@@ -192,4 +192,4 @@ async function updateImage(sessionFolder, path, update) {
192
192
  //#endregion
193
193
  export { updateImage as i, galleryFile as n, listGallery as r, describeGalleryImage as t };
194
194
 
195
- //# sourceMappingURL=gallery-DUeBMHQX.js.map
195
+ //# sourceMappingURL=gallery-DACG5eh2.js.map
@@ -846,6 +846,6 @@ async function generateTransientImage(service, request) {
846
846
  return path;
847
847
  }
848
848
  //#endregion
849
- export { runChild as A, norm as C, childSampling as D, childModel as E, childSamplingOf as O, mapLimit as S, uniqueKey as T, readImageFileMetadata as _, uploadReferenceImage as a, readPngMetadata as b, LIBRARY_FOLDER as c, nextSceneSerial as d, readImageMetadata as f, mediaTypeOf as g, MEDIA_TYPES as h, transientPrompt as i, estimateAnswer as j, childTrace as k, entityImageDirectory as l, sceneImagePath as m, generateTransientImage as n, addToLibrary as o, referenceImagePath as p, referencePrompt as r, imageExtensionOf as s, generateReferenceImage as t, inheritImages as u, sidecarOf as v, slug as w, withPngMetadata as x, writeImageFileMetadata as y };
849
+ export { runChild as A, norm as C, childSampling as D, childModel as E, tokensOf as M, childSamplingOf as O, mapLimit as S, uniqueKey as T, readImageFileMetadata as _, uploadReferenceImage as a, readPngMetadata as b, LIBRARY_FOLDER as c, nextSceneSerial as d, readImageMetadata as f, mediaTypeOf as g, MEDIA_TYPES as h, transientPrompt as i, estimateAnswer as j, childTrace as k, entityImageDirectory as l, sceneImagePath as m, generateTransientImage as n, addToLibrary as o, referenceImagePath as p, referencePrompt as r, imageExtensionOf as s, generateReferenceImage as t, inheritImages as u, sidecarOf as v, slug as w, withPngMetadata as x, writeImageFileMetadata as y };
850
850
 
851
- //# sourceMappingURL=generator-HPifO3Kk.js.map
851
+ //# sourceMappingURL=generator-DGYcLMp7.js.map
package/lib/images.js CHANGED
@@ -1,4 +1,4 @@
1
- import { b as readPngMetadata, d as nextSceneSerial, f as readImageMetadata, i as transientPrompt, l as entityImageDirectory, m as sceneImagePath, n as generateTransientImage, o as addToLibrary, p as referenceImagePath, r as referencePrompt, t as generateReferenceImage, u as inheritImages, x as withPngMetadata } from "./generator-HPifO3Kk.js";
2
- import { i as updateImage, r as listGallery } from "./gallery-DUeBMHQX.js";
3
- import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PX1WVaJB.js";
1
+ import { b as readPngMetadata, d as nextSceneSerial, f as readImageMetadata, i as transientPrompt, l as entityImageDirectory, m as sceneImagePath, n as generateTransientImage, o as addToLibrary, p as referenceImagePath, r as referencePrompt, t as generateReferenceImage, u as inheritImages, x as withPngMetadata } from "./generator-DGYcLMp7.js";
2
+ import { i as updateImage, r as listGallery } from "./gallery-DACG5eh2.js";
3
+ import { a as tokensOf, i as searchImages, n as interpretImage, o as present, r as imageTools, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PK9JYExk.js";
4
4
  export { addToLibrary, entityImageDirectory, generateReferenceImage, generateTransientImage, imageTools, inheritImages, interpretImage, listGallery, nextSceneSerial, present, presentedFor, readImageMetadata, readPngMetadata, referenceImagePath, referencePrompt, runImagePresenter, sceneImagePath, searchImages, tokensOf, transientPrompt, updateImage, withPngMetadata };
package/lib/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
- import { $ as writeWorldPrompt, B as populateTriggers, C as authoringChatSessionId, F as populateItems, G as loadItems, H as routineProblems, I as populateKnowledge, J as subfolders, K as CHARACTERS_DIR, L as populateLocations, M as populateCharacters, N as populateClock, P as populateFactions, Q as readWorldPrompt, R as populateLore, V as populateVariables, W as loadLocations, X as deleteWorldPrompt, Z as listWorldPrompts, _ as replaceFile$1, _t as parseRelationEdit, at as IMPORT_FOLDER, c as editWorldLore$1, ct as parseChoices, d as editWorldPlots$1, dt as parseWorldInfoEdit, et as VARIABLES_FILE_NAME, f as editWorldRelation$1, ft as InvalidEditProblems, g as readWorldEditor, gt as parsePlaceEdit, h as generateWorldCharacterPortrait, ht as parseLoreEdit, i as readAuthoredEntityDocument, it as parseCharacterFile, j as loadValidatedWorld, k as markReady, l as editWorldNarrationVoice, lt as WORLD_FILE_NAME, m as entityFolder, mt as parseFactionEdit, n as createAuthoredEntity, nt as variableProblems, o as editWorldCharacter$1, ot as ImportNotFoundError, p as editWorldThing$1, pt as parseCharacterEdit, q as loadCharacters, r as deleteAuthoredEntity, rt as CHARACTER_FILE_NAME, s as editWorldFaction$1, st as ImportStore, tt as parseVariablesFile, u as editWorldPlace$1, ut as parseWorldFile, v as uploadWorldCharacterPortrait, vt as parseThingEdit, x as loadWorldParts, y as worldCharacterPortraitFile, yt as IMPORT_COMMAND, z as populateRoutines } from "./documents-7GMc5NnW.js";
3
- import { A as languageOf, B as SessionArchivedError, C as errorMessage, D as PromptLibrary, H as WorldNotFoundError, I as AgentUnavailableError, L as InvalidStartError, O as copyWorldPrompts, R as InvalidWorldError, S as readDocument$1, T as formatIssue, V as SessionNotFoundError, _ as API_PREFIX, a as packIds, b as parsePlotsFile, c as describePack, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile, x as plotReferenceProblems, z as ReflectionRefusedError } from "./packs-alJTiDM2.js";
4
- import { A as readTimeline, C as notesOfSession, E as observeAsPlayer, M as defaultBoundaries, O as TimelineError, T as readNotes, V as zoneOf, a as readActivity, d as reflectionStatus, j as pathTo, n as readWithdrawn, o as readRunDetail, p as PLOTS_METADATA_KEY, v as plotProgressOf, x as addToNote, y as populatePlots } from "./deliver--uMhC6oO.js";
5
- import { a as liveSettings, c as writeSettings, d as parseSettings, f as WORLD_RULES_KEY, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-CKZTk5UE.js";
2
+ import { $ as subfolders, B as populateLore, Ct as parseThingEdit, D as authoringChatSessionId, F as populateClock, G as TRIGGERS_FILE_NAME, H as populateTriggers, I as populateFactions, J as parseCalendarFile, K as CALENDAR_FILE_NAME, L as populateItems, M as loadValidatedWorld, N as populateCalendar, O as languageOfDocuments, P as populateCharacters, Q as loadCharacters, R as populateKnowledge, S as translateMessage, St as parseRelationEdit, U as populateVariables, V as populateRoutines, W as routineProblems, X as loadItems, Y as loadLocations, Z as CHARACTERS_DIR, _ as replaceFile$1, _t as InvalidEditProblems, at as VARIABLES_FILE_NAME, bt as parseLoreEdit, c as editWorldLore$1, ct as CHARACTER_FILE_NAME, d as editWorldPlots$1, dt as ImportNotFoundError, f as editWorldRelation$1, ft as ImportStore, g as readWorldEditor, gt as parseWorldInfoEdit, h as generateWorldCharacterPortrait, ht as parseWorldFile, i as readAuthoredEntityDocument, it as writeWorldPrompt, j as markReady, k as readWorldDocuments, l as editWorldNarrationVoice, lt as parseCharacterFile, m as entityFolder, mt as WORLD_FILE_NAME, n as createAuthoredEntity, nt as listWorldPrompts, o as editWorldCharacter$1, ot as parseVariablesFile, p as editWorldThing$1, pt as parseChoices, q as loadCalendar, r as deleteAuthoredEntity, rt as readWorldPrompt, s as editWorldFaction$1, st as variableProblems, tt as deleteWorldPrompt, u as editWorldPlace$1, ut as IMPORT_FOLDER, v as uploadWorldCharacterPortrait, vt as parseCharacterEdit, wt as IMPORT_COMMAND, x as loadWorldParts, xt as parsePlaceEdit, y as worldCharacterPortraitFile, yt as parseFactionEdit, z as populateLocations } from "./documents-DtlY2IRt.js";
3
+ import { A as formatIssue, D as readDocument$1, E as plotReferenceProblems, F as languageOf, G as SessionArchivedError, H as InvalidStartError, K as SessionNotFoundError, M as PromptLibrary, N as copyWorldPrompts, O as errorMessage, T as parsePlotsFile, U as InvalidWorldError, V as AgentUnavailableError, W as ReflectionRefusedError, _ as API_PREFIX, a as packIds, c as describePack, f as readPack, l as isPackId, m as PACK_LIMITS, n as anyTab, o as syncWorldPacks, q as WorldNotFoundError, r as copyWorldPacks, s as worldPackStates, t as activePack, u as packFile } from "./packs-CkRZDCsV.js";
4
+ import { A as readTimeline, C as notesOfSession, E as observeAsPlayer, M as defaultBoundaries, O as TimelineError, T as readNotes, V as zoneOf, a as readActivity, d as reflectionStatus, j as pathTo, n as readWithdrawn, o as readRunDetail, p as PLOTS_METADATA_KEY, v as plotProgressOf, x as addToNote, y as populatePlots } from "./deliver-BDW5WZvc.js";
5
+ import { a as liveSettings, c as writeSettings, d as parseSettings, f as WORLD_RULES_KEY, i as InvalidSettingsError, l as DEFAULT_SETTINGS, n as encodeOutput, o as readSettings, s as useChildReasoning, u as SETTINGS_SPEC } from "./narration-5ig7Dg28.js";
6
6
  import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
7
- import { O as childSamplingOf, T as uniqueKey, a as uploadReferenceImage, m as sceneImagePath, o as addToLibrary, p as referenceImagePath, t as generateReferenceImage, u as inheritImages, w as slug } from "./generator-HPifO3Kk.js";
8
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DUeBMHQX.js";
7
+ import { O as childSamplingOf, T as uniqueKey, a as uploadReferenceImage, m as sceneImagePath, o as addToLibrary, p as referenceImagePath, t as generateReferenceImage, u as inheritImages, w as slug } from "./generator-DGYcLMp7.js";
8
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DACG5eh2.js";
9
9
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
10
10
  import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
11
11
  import { createHash, randomBytes, randomUUID } from "node:crypto";
@@ -16,7 +16,7 @@ import { inflateSync } from "node:zlib";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { Service } from "@deepseek-ai/cordis";
18
18
  import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
19
- import { createSessionStore, describeInstant, describeValue, isSessionId, itemKey, lintWorld, locationKey, parseInstant, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
19
+ import { addLocalDays, createSessionStore, describeInstant, describeValue, holidaysOn, isSessionId, itemKey, lintWorld, locationKey, parseInstant, readCalendar, seasonOf, sessionDatabase, sessionFolder, shownVariables, systemTimeZone } from "@dsh-agentic-roleplay/state";
20
20
  import { pipeline } from "node:stream/promises";
21
21
  import { homedir } from "node:os";
22
22
  import z from "@deepseek-ai/schemastery";
@@ -615,6 +615,39 @@ async function startImport(deps, id, choices, language) {
615
615
  };
616
616
  }
617
617
  //#endregion
618
+ //#region src/host/translate/service.ts
619
+ async function recordOf(worlds, id) {
620
+ const record = await worlds.find(id);
621
+ if (record === void 0) throw new WorldNotFoundError(`there is no world with id "${id}"`);
622
+ return record;
623
+ }
624
+ /** The language a world is written in, from the words of its files; nothing when there is too little text to tell. */
625
+ async function worldLanguage(worlds, id) {
626
+ return languageOfDocuments(await readWorldDocuments((await recordOf(worlds, id)).directory));
627
+ }
628
+ /** Opens the authoring chat of a world and asks it to translate the world; the work shows in that chat. */
629
+ async function startTranslation(deps, id, to, title, language) {
630
+ const record = await recordOf(deps.worlds, id);
631
+ const from = await worldLanguage(deps.worlds, id);
632
+ if (from === void 0) throw new InvalidEditProblems(["there is too little text in this world to tell which language it is written in"]);
633
+ if (from === to) throw new InvalidEditProblems([`this world is already written in ${to === "zh" ? "Chinese" : "English"}`]);
634
+ const chatSessionId = await deps.authoring.ensure(record.summary.id, record.summary.name, title, language);
635
+ const told = language.startsWith("zh") ? "zh" : "en";
636
+ try {
637
+ await deps.authoring.send(chatSessionId, translateMessage((key, variables) => deps.text(key, language, variables), to, told));
638
+ return {
639
+ chatSessionId,
640
+ started: true
641
+ };
642
+ } catch (error) {
643
+ return {
644
+ chatSessionId,
645
+ started: false,
646
+ failure: error instanceof Error ? error.message : String(error)
647
+ };
648
+ }
649
+ }
650
+ //#endregion
618
651
  //#region src/host/agent/authoring-sessions.ts
619
652
  const AUTHORING_PROJECT_TITLE = "World Authoring";
620
653
  const AUTHORING_AGENT_PRESET = "world-authoring";
@@ -711,6 +744,7 @@ var RoleplayOrchestration = class extends Service {
711
744
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
712
745
  const ROUTINE_FIELDS = [
713
746
  "days",
747
+ "on",
714
748
  "from",
715
749
  "to",
716
750
  "activity",
@@ -755,6 +789,7 @@ function parseRoutineEdit(value) {
755
789
  const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
756
790
  return {
757
791
  days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
792
+ ...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
758
793
  from: text("from"),
759
794
  to: text("to"),
760
795
  activity: text("activity"),
@@ -864,6 +899,45 @@ function parseVariablesEdit(value) {
864
899
  if (problems.length > 0) throw new InvalidEditProblems(problems);
865
900
  return declarations;
866
901
  }
902
+ /**
903
+ * The calendar as the browser sends it.
904
+ * @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
905
+ */
906
+ function parseCalendarEdit(value) {
907
+ const problems = [];
908
+ if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
909
+ if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
910
+ const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
911
+ if (list === void 0) problems.push("holidays must be a list");
912
+ const holidays = (list ?? []).map((entry, index) => {
913
+ const at = `holidays[${index}]`;
914
+ if (!isObject(entry)) {
915
+ problems.push(`${at} must be an object`);
916
+ return {
917
+ id: "",
918
+ name: "",
919
+ on: []
920
+ };
921
+ }
922
+ for (const key of Object.keys(entry)) if (![
923
+ "id",
924
+ "name",
925
+ "on"
926
+ ].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
927
+ for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
928
+ if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
929
+ return {
930
+ id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
931
+ name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
932
+ on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
933
+ };
934
+ });
935
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
936
+ return {
937
+ hemisphere: value["hemisphere"],
938
+ holidays
939
+ };
940
+ }
867
941
  //#endregion
868
942
  //#region src/host/worlds/starter.ts
869
943
  const STARTER_FOLDER = "starter-worlds";
@@ -1131,10 +1205,14 @@ function playerViewOf(session, options) {
1131
1205
  const clock = session.clock.get();
1132
1206
  if (clock !== void 0) {
1133
1207
  const now = clock.mode === "real" ? options.wall : clock.now;
1208
+ const calendar = readCalendar(session.metadata);
1209
+ const day = addLocalDays(now, options.zone, 0);
1134
1210
  view.time = {
1135
1211
  iso: new Date(now).toISOString(),
1136
1212
  zone: options.zone,
1137
- text: describeInstant(now, options.zone)
1213
+ text: describeInstant(now, options.zone),
1214
+ season: seasonOf(day, calendar.hemisphere),
1215
+ holidays: holidaysOn(calendar, day).map((holiday) => holiday.name)
1138
1216
  };
1139
1217
  }
1140
1218
  view.variables.push(...shown("the world", shownVariables(session, "world", 0, "world", "others")));
@@ -1764,7 +1842,7 @@ function languageField(value) {
1764
1842
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
1765
1843
  }
1766
1844
  }
1767
- function createApiHandler({ worlds, createWorld, starter, authorWorld, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech }) {
1845
+ function createApiHandler({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech }) {
1768
1846
  const routes = {
1769
1847
  "/speech/capabilities": { GET: async (_req, res) => {
1770
1848
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1883,6 +1961,30 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
1883
1961
  throw error;
1884
1962
  }
1885
1963
  } },
1964
+ "/worlds/language": { GET: async (_req, res, url) => {
1965
+ try {
1966
+ sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
1967
+ } catch (error) {
1968
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1969
+ throw error;
1970
+ }
1971
+ } },
1972
+ "/worlds/translate": { POST: async (req, res, url) => {
1973
+ const body = await readJsonBody(req);
1974
+ if (body.to !== "en" && body.to !== "zh") return sendError(res, 400, "to must be \"en\" or \"zh\"");
1975
+ if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
1976
+ try {
1977
+ sendJson(res, 200, await translation.start(url.searchParams.get("id") ?? "", body.to, body.title.trim(), languageField(body.language) ?? "en"));
1978
+ } catch (error) {
1979
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1980
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
1981
+ message: error.message,
1982
+ problems: error.problems
1983
+ });
1984
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
1985
+ throw error;
1986
+ }
1987
+ } },
1886
1988
  "/avatars": {
1887
1989
  POST: async (req, res) => {
1888
1990
  const body = await readJsonBody(req);
@@ -2066,6 +2168,28 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
2066
2168
  throw error;
2067
2169
  }
2068
2170
  } },
2171
+ "/worlds/calendar": {
2172
+ GET: async (_req, res, url) => {
2173
+ try {
2174
+ sendJson(res, 200, await worldFiles.calendar(url.searchParams.get("id") ?? ""));
2175
+ } catch (error) {
2176
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2177
+ throw error;
2178
+ }
2179
+ },
2180
+ PUT: async (req, res, url) => {
2181
+ try {
2182
+ sendJson(res, 200, await worldFiles.editCalendar(url.searchParams.get("id") ?? "", parseCalendarEdit(await readJsonBody(req))));
2183
+ } catch (error) {
2184
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2185
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2186
+ message: error.message,
2187
+ problems: error.problems
2188
+ });
2189
+ throw error;
2190
+ }
2191
+ }
2192
+ },
2069
2193
  "/worlds/variables": {
2070
2194
  GET: async (_req, res, url) => {
2071
2195
  try {
@@ -2876,7 +3000,8 @@ async function editRoutine(world, key, windows) {
2876
3000
  const parsed = parseCharacterFile(next, folder);
2877
3001
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
2878
3002
  const { locations } = await loadLocations(world.directory);
2879
- const places = routineProblems([parsed.value], locations);
3003
+ const { calendar } = await loadCalendar(world.directory);
3004
+ const places = routineProblems([parsed.value], locations, calendar);
2880
3005
  if (places.length > 0) throw new InvalidEditProblems(places);
2881
3006
  await replaceFile$1(file, next);
2882
3007
  return await readRoutines(world);
@@ -2926,6 +3051,40 @@ async function replaceFileOrCreate(file, text) {
2926
3051
  await writeFile(file, text, { flag: "wx" });
2927
3052
  }
2928
3053
  }
3054
+ /** The calendar of the world as `calendar.json` writes it; a world without one has the northern seasons and no holidays. */
3055
+ async function readCalendarDocument(world) {
3056
+ const { calendar } = await loadCalendar(world.directory);
3057
+ return {
3058
+ hemisphere: calendar.hemisphere,
3059
+ holidays: calendar.holidays.map((holiday) => ({
3060
+ id: holiday.id,
3061
+ name: holiday.name,
3062
+ on: [...holiday.on]
3063
+ }))
3064
+ };
3065
+ }
3066
+ /**
3067
+ * Replaces the calendar. The days are read as the file is at a start, and a holiday that a routine of a character or a trigger still names cannot be removed or renamed.
3068
+ * A calendar with no holidays and the northern seasons is no file at all.
3069
+ * @throws {InvalidEditProblems} naming each problem; nothing is written.
3070
+ */
3071
+ async function editCalendar(world, calendar) {
3072
+ const text = `${JSON.stringify(calendar, null, 2)}\n`;
3073
+ const parsed = parseCalendarFile(text);
3074
+ if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
3075
+ const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
3076
+ const problems = routineProblems(characters, locations, parsed.value);
3077
+ const triggers = await readFile(join(world.directory, TRIGGERS_FILE_NAME), "utf8").catch((error) => {
3078
+ if (error.code === "ENOENT") return "";
3079
+ throw error;
3080
+ });
3081
+ const named = new Set(calendar.holidays.map((holiday) => holiday.id));
3082
+ for (const id of new Set([...triggers.matchAll(/holiday:([\p{L}\p{N}_-]+)/gu)].map((match) => match[1]))) if (!named.has(id)) problems.push(`a trigger names the holiday "${id}", which the calendar does not have`);
3083
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
3084
+ if (calendar.holidays.length === 0 && calendar.hemisphere === "north") await rm(join(world.directory, CALENDAR_FILE_NAME), { force: true });
3085
+ else await replaceFileOrCreate(join(world.directory, CALENDAR_FILE_NAME), text);
3086
+ return await readCalendarDocument(world);
3087
+ }
2929
3088
  //#endregion
2930
3089
  //#region src/host/worlds/lore-entries.ts
2931
3090
  const MAX_TITLE = 200;
@@ -3853,7 +4012,7 @@ function worldFindings(session) {
3853
4012
  async function startSession(deps, request) {
3854
4013
  const world = await deps.worlds.find(request.worldId);
3855
4014
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
3856
- const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots } = await loadValidatedWorld(world);
4015
+ const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar } = await loadValidatedWorld(world);
3857
4016
  if (request.opening !== void 0 && (!Number.isInteger(request.opening) || request.opening < 0 || request.opening >= (world.alternateOpenings?.length ?? 0))) throw new InvalidStartError(`the world has no alternate opening ${String(request.opening)}`);
3858
4017
  const opening = request.opening === void 0 ? openingOf(world, authored) : [{
3859
4018
  type: "narration",
@@ -3911,6 +4070,7 @@ async function startSession(deps, request) {
3911
4070
  populateLocations(session, locations);
3912
4071
  populateCharacters(session, characters, player.id);
3913
4072
  populateFactions(session, factions);
4073
+ populateCalendar(session, calendar);
3914
4074
  populateRoutines(session, characters);
3915
4075
  populateItems(session, items, slots, locations);
3916
4076
  populateLore(session, authoredLore.lore);
@@ -4699,6 +4859,14 @@ function apply(ctx, config) {
4699
4859
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
4700
4860
  return { chatSessionId: await authoring.ensure(world.summary.id, world.summary.name, title, language) };
4701
4861
  },
4862
+ translation: {
4863
+ language: (id) => worldLanguage(worlds, id),
4864
+ start: (id, to, title, language) => startTranslation({
4865
+ worlds,
4866
+ authoring,
4867
+ text: (key, lang, variables) => prompts.text(key, lang, variables)
4868
+ }, id, to, title, language)
4869
+ },
4702
4870
  importer: {
4703
4871
  maxUploadBytes: config.importMaxUploadBytes,
4704
4872
  upload: async (file, name) => {
@@ -4737,6 +4905,8 @@ function apply(ctx, config) {
4737
4905
  },
4738
4906
  routines: async (worldId) => await readRoutines(await editableWorld(worlds, worldId, root.path)),
4739
4907
  editRoutine: async (worldId, key, windows) => await editRoutine(await editableWorld(worlds, worldId, root.path), key, windows),
4908
+ calendar: async (worldId) => await readCalendarDocument(await editableWorld(worlds, worldId, root.path)),
4909
+ editCalendar: async (worldId, calendar) => await editCalendar(await editableWorld(worlds, worldId, root.path), calendar),
4740
4910
  variables: async (worldId) => await readVariables(await editableWorld(worlds, worldId, root.path)),
4741
4911
  editVariables: async (worldId, declarations) => await editVariables(await editableWorld(worlds, worldId, root.path), declarations),
4742
4912
  prompts: async (worldId, language) => listWorldPrompts((await editableWorld(worlds, worldId, root.path)).directory, language),
@@ -59,7 +59,8 @@ const SETTINGS_SPEC = {
59
59
  backlogRounds: integer(1, 100, 6),
60
60
  overRetrieve: integer(1, 10, 4),
61
61
  associate: integer(0, 10, 2),
62
- diversity: ratio(0, 1, .3)
62
+ diversity: ratio(0, 1, .3),
63
+ foldedFade: ratio(.05, 1, .5)
63
64
  },
64
65
  context: {
65
66
  limitTokens: integer(0, 1e6, 0),
@@ -364,4 +365,4 @@ function decodeOutput(text) {
364
365
  //#endregion
365
366
  export { liveSettings as a, writeSettings as c, parseSettings as d, WORLD_RULES_KEY as f, InvalidSettingsError as i, DEFAULT_SETTINGS as l, encodeOutput as n, readSettings as o, rulesOf as p, encodePreview as r, useChildReasoning as s, decodeOutput as t, SETTINGS_SPEC as u };
366
367
 
367
- //# sourceMappingURL=narration-CKZTk5UE.js.map
368
+ //# sourceMappingURL=narration-5ig7Dg28.js.map