@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,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-BzeepLd2.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-DS5-qH9F.js.map
@@ -311,7 +311,7 @@ async function execute(task, stats) {
311
311
  appendDelegatedPolicyOverrides(child.session, inherited);
312
312
  applyChildComposition(childCtx, parent, {
313
313
  persona: `${task.persona}\n\n${SUBMIT_RULE}`,
314
- toolFilter: { allow: [] }
314
+ toolFilter: { allow: [...task.external ?? []] }
315
315
  });
316
316
  const registered = (task.tools ?? []).map((tool) => childCtx.tools.register(counted(tool)));
317
317
  retire = () => {
@@ -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-BzeepLd2.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-BzeepLd2.js";
2
+ import { i as updateImage, r as listGallery } from "./gallery-DS5-qH9F.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-Cp-J0onD.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";
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";
2
+ import { $ as loadLocations, At as DICE_COMPARISONS, B as populateLocations, Ct as parseCharacterEdit, D as authoringChatSessionId, Dt as parseRelationEdit, Et as parsePlaceEdit, F as populateClock, G as routineProblems, H as populateRoutines, I as populateDice, J as loadDice, K as TRIGGERS_FILE_NAME, L as populateFactions, M as loadValidatedWorld, Mt as DICE_RESULTS, N as populateCalendar, O as languageOfDocuments, Ot as parseThingEdit, P as populateCharacters, Q as parseCalendarFile, R as populateItems, S as translateMessage, St as InvalidEditProblems, Tt as parseLoreEdit, U as populateTriggers, V as populateLore, W as populateVariables, X as CALENDAR_FILE_NAME, Y as parseDiceFile, Z as loadCalendar, _ as replaceFile$1, _t as ImportStore, at as deleteWorldPrompt, bt as parseWorldFile, c as editWorldLore$1, ct as writeWorldPrompt, d as editWorldPlots$1, dt as parseVariablesFile, et as loadItems, f as editWorldRelation$1, ft as variableProblems, g as readWorldEditor, gt as ImportNotFoundError, h as generateWorldCharacterPortrait, ht as IMPORT_FOLDER, i as readAuthoredEntityDocument, j as markReady, jt as DICE_READINGS, k as readWorldDocuments, kt as IMPORT_COMMAND, l as editWorldNarrationVoice, lt as VARIABLES_FILE_NAME, m as entityFolder, mt as parseCharacterFile, n as createAuthoredEntity, nt as loadCharacters, o as editWorldCharacter$1, ot as listWorldPrompts, p as editWorldThing$1, pt as CHARACTER_FILE_NAME, q as DICE_FILE_NAME, r as deleteAuthoredEntity, rt as subfolders, s as editWorldFaction$1, st as readWorldPrompt, tt as CHARACTERS_DIR, u as editWorldPlace$1, ut as loadVariables, v as uploadWorldCharacterPortrait, vt as parseChoices, wt as parseFactionEdit, x as loadWorldParts, xt as parseWorldInfoEdit, y as worldCharacterPortraitFile, yt as WORLD_FILE_NAME, z as populateKnowledge } from "./documents-B5XAdfo2.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-BCGK9KZV.js";
4
+ import { A as notesOfSession, C as plotProgressOf, F as TimelineError, L as readTimeline, M as readNotes, N as observeAsPlayer, O as addToNote, R as pathTo, a as readActivity, d as reflectionStatus, m as externalTools, n as readWithdrawn, o as readRunDetail, q as zoneOf, w as populatePlots, y as PLOTS_METADATA_KEY, z as defaultBoundaries } from "./deliver-BSsDtF6X.js";
5
+ import { a as WORLD_RULES_KEY, c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, n as SETTINGS_SPEC, r as parseSettings, s as VARIABLE_KINDS, t as DEFAULT_SETTINGS } from "./settings-CA6icLL_.js";
6
+ import { a as liveSettings, c as writeSettings, i as InvalidSettingsError, n as encodeOutput, o as readSettings, s as useChildReasoning } from "./narration-DK2kiIjE.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-BzeepLd2.js";
8
+ import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-DS5-qH9F.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";
@@ -707,10 +740,101 @@ var RoleplayOrchestration = class extends Service {
707
740
  }
708
741
  };
709
742
  //#endregion
743
+ //#region src/shared/world-dice.ts
744
+ const isObject$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
745
+ const CHECK_FIELDS = [
746
+ "key",
747
+ "name",
748
+ "use",
749
+ "dice",
750
+ "reading",
751
+ "hit",
752
+ "compare",
753
+ "modifier",
754
+ "bands"
755
+ ];
756
+ const BAND_FIELDS = [
757
+ "min",
758
+ "max",
759
+ "label",
760
+ "result",
761
+ "critical"
762
+ ];
763
+ /** Reads a body that came from the browser: the shape of every field is checked here, and what the checks mean when the world is validated. */
764
+ function parseDiceEdit(value) {
765
+ const problems = [];
766
+ if (!isObject$1(value) || !Array.isArray(value["checks"])) throw new InvalidEditProblems(["the dice must be { checks: [...] }"]);
767
+ const checks = value["checks"].map((entry, index) => {
768
+ const at = `checks[${index}]`;
769
+ const empty = {
770
+ key: "",
771
+ name: "",
772
+ use: "",
773
+ dice: "",
774
+ bands: []
775
+ };
776
+ if (!isObject$1(entry)) {
777
+ problems.push(`${at} must be an object`);
778
+ return empty;
779
+ }
780
+ for (const key of Object.keys(entry)) if (!CHECK_FIELDS.includes(key)) problems.push(`${at}.${key} is not a field of a check`);
781
+ for (const key of [
782
+ "key",
783
+ "name",
784
+ "use",
785
+ "dice"
786
+ ]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
787
+ if (entry["reading"] !== void 0 && !DICE_READINGS.includes(entry["reading"])) problems.push(`${at}.reading must be one of: ${DICE_READINGS.join(", ")}`);
788
+ if (entry["compare"] !== void 0 && !DICE_COMPARISONS.includes(entry["compare"])) problems.push(`${at}.compare must be one of: ${DICE_COMPARISONS.join(", ")}`);
789
+ if (entry["hit"] !== void 0 && (typeof entry["hit"] !== "number" || !Number.isInteger(entry["hit"]))) problems.push(`${at}.hit must be a whole number`);
790
+ if (entry["modifier"] !== void 0 && typeof entry["modifier"] !== "string") problems.push(`${at}.modifier must be text`);
791
+ const bands = Array.isArray(entry["bands"]) ? entry["bands"] : void 0;
792
+ if (bands === void 0) problems.push(`${at}.bands must be a list`);
793
+ const text = (field) => typeof field === "string" ? field.trim() : "";
794
+ const hit = entry["hit"];
795
+ return {
796
+ key: text(entry["key"]),
797
+ name: text(entry["name"]),
798
+ use: text(entry["use"]),
799
+ dice: text(entry["dice"]),
800
+ ...entry["reading"] === void 0 ? {} : { reading: entry["reading"] },
801
+ ...typeof hit === "number" ? { hit } : {},
802
+ ...entry["compare"] === void 0 ? {} : { compare: entry["compare"] },
803
+ ...text(entry["modifier"]) === "" ? {} : { modifier: text(entry["modifier"]) },
804
+ bands: (bands ?? []).map((band, bandIndex) => {
805
+ const where = `${at}.bands[${bandIndex}]`;
806
+ if (!isObject$1(band)) {
807
+ problems.push(`${where} must be an object`);
808
+ return {
809
+ label: "",
810
+ result: "failed"
811
+ };
812
+ }
813
+ for (const key of Object.keys(band)) if (!BAND_FIELDS.includes(key)) problems.push(`${where}.${key} is not a field of a band`);
814
+ for (const key of ["min", "max"]) if (band[key] !== void 0 && (typeof band[key] !== "number" || !Number.isFinite(band[key]))) problems.push(`${where}.${key} must be a number`);
815
+ if (typeof band["label"] !== "string") problems.push(`${where}.label must be text`);
816
+ if (!DICE_RESULTS.includes(band["result"])) problems.push(`${where}.result must be one of: ${DICE_RESULTS.join(", ")}`);
817
+ const min = band["min"];
818
+ const max = band["max"];
819
+ return {
820
+ label: text(band["label"]),
821
+ result: band["result"],
822
+ ...typeof min === "number" ? { min } : {},
823
+ ...typeof max === "number" ? { max } : {},
824
+ ...band["critical"] === true ? { critical: true } : {}
825
+ };
826
+ })
827
+ };
828
+ });
829
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
830
+ return { checks };
831
+ }
832
+ //#endregion
710
833
  //#region src/shared/world-daily.ts
711
834
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
712
835
  const ROUTINE_FIELDS = [
713
836
  "days",
837
+ "on",
714
838
  "from",
715
839
  "to",
716
840
  "activity",
@@ -755,6 +879,7 @@ function parseRoutineEdit(value) {
755
879
  const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
756
880
  return {
757
881
  days: Array.isArray(entry["days"]) ? entry["days"].map((day) => day.trim().toLowerCase()).filter((day) => day !== "") : [],
882
+ ...Array.isArray(entry["on"]) && entry["on"].length > 0 ? { on: entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") } : {},
758
883
  from: text("from"),
759
884
  to: text("to"),
760
885
  activity: text("activity"),
@@ -864,6 +989,45 @@ function parseVariablesEdit(value) {
864
989
  if (problems.length > 0) throw new InvalidEditProblems(problems);
865
990
  return declarations;
866
991
  }
992
+ /**
993
+ * The calendar as the browser sends it.
994
+ * @throws {InvalidEditProblems} naming every field that has the wrong shape; whether the days and ids are acceptable is checked as the file is read.
995
+ */
996
+ function parseCalendarEdit(value) {
997
+ const problems = [];
998
+ if (!isObject(value)) throw new InvalidEditProblems(["the calendar must be { hemisphere, holidays: [...] }"]);
999
+ if (value["hemisphere"] !== "north" && value["hemisphere"] !== "south") problems.push("hemisphere must be \"north\" or \"south\"");
1000
+ const list = Array.isArray(value["holidays"]) ? value["holidays"] : void 0;
1001
+ if (list === void 0) problems.push("holidays must be a list");
1002
+ const holidays = (list ?? []).map((entry, index) => {
1003
+ const at = `holidays[${index}]`;
1004
+ if (!isObject(entry)) {
1005
+ problems.push(`${at} must be an object`);
1006
+ return {
1007
+ id: "",
1008
+ name: "",
1009
+ on: []
1010
+ };
1011
+ }
1012
+ for (const key of Object.keys(entry)) if (![
1013
+ "id",
1014
+ "name",
1015
+ "on"
1016
+ ].includes(key)) problems.push(`${at}.${key} is not a field of a holiday`);
1017
+ for (const key of ["id", "name"]) if (typeof entry[key] !== "string") problems.push(`${at}.${key} must be text`);
1018
+ if (!(Array.isArray(entry["on"]) && entry["on"].every((day) => typeof day === "string"))) problems.push(`${at}.on must be a list of days`);
1019
+ return {
1020
+ id: typeof entry["id"] === "string" ? entry["id"].trim() : "",
1021
+ name: typeof entry["name"] === "string" ? entry["name"].trim() : "",
1022
+ on: Array.isArray(entry["on"]) ? entry["on"].map((day) => String(day).trim()).filter((day) => day !== "") : []
1023
+ };
1024
+ });
1025
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
1026
+ return {
1027
+ hemisphere: value["hemisphere"],
1028
+ holidays
1029
+ };
1030
+ }
867
1031
  //#endregion
868
1032
  //#region src/host/worlds/starter.ts
869
1033
  const STARTER_FOLDER = "starter-worlds";
@@ -1131,10 +1295,14 @@ function playerViewOf(session, options) {
1131
1295
  const clock = session.clock.get();
1132
1296
  if (clock !== void 0) {
1133
1297
  const now = clock.mode === "real" ? options.wall : clock.now;
1298
+ const calendar = readCalendar(session.metadata);
1299
+ const day = addLocalDays(now, options.zone, 0);
1134
1300
  view.time = {
1135
1301
  iso: new Date(now).toISOString(),
1136
1302
  zone: options.zone,
1137
- text: describeInstant(now, options.zone)
1303
+ text: describeInstant(now, options.zone),
1304
+ season: seasonOf(day, calendar.hemisphere),
1305
+ holidays: holidaysOn(calendar, day).map((holiday) => holiday.name)
1138
1306
  };
1139
1307
  }
1140
1308
  view.variables.push(...shown("the world", shownVariables(session, "world", 0, "world", "others")));
@@ -1764,7 +1932,7 @@ function languageField(value) {
1764
1932
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
1765
1933
  }
1766
1934
  }
1767
- function createApiHandler({ worlds, createWorld, starter, authorWorld, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech }) {
1935
+ function createApiHandler({ worlds, createWorld, starter, authorWorld, translation, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech, externalTools }) {
1768
1936
  const routes = {
1769
1937
  "/speech/capabilities": { GET: async (_req, res) => {
1770
1938
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1883,6 +2051,30 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
1883
2051
  throw error;
1884
2052
  }
1885
2053
  } },
2054
+ "/worlds/language": { GET: async (_req, res, url) => {
2055
+ try {
2056
+ sendJson(res, 200, { language: await translation.language(url.searchParams.get("id") ?? "") ?? null });
2057
+ } catch (error) {
2058
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2059
+ throw error;
2060
+ }
2061
+ } },
2062
+ "/worlds/translate": { POST: async (req, res, url) => {
2063
+ const body = await readJsonBody(req);
2064
+ if (body.to !== "en" && body.to !== "zh") return sendError(res, 400, "to must be \"en\" or \"zh\"");
2065
+ if (typeof body.title !== "string" || body.title.trim() === "" || body.title.length > 300) return sendError(res, 400, "the request needs a valid chat title");
2066
+ try {
2067
+ sendJson(res, 200, await translation.start(url.searchParams.get("id") ?? "", body.to, body.title.trim(), languageField(body.language) ?? "en"));
2068
+ } catch (error) {
2069
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2070
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2071
+ message: error.message,
2072
+ problems: error.problems
2073
+ });
2074
+ if (error instanceof AgentUnavailableError) return sendError(res, 503, error.message);
2075
+ throw error;
2076
+ }
2077
+ } },
1886
2078
  "/avatars": {
1887
2079
  POST: async (req, res) => {
1888
2080
  const body = await readJsonBody(req);
@@ -2066,6 +2258,50 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
2066
2258
  throw error;
2067
2259
  }
2068
2260
  } },
2261
+ "/worlds/dice": {
2262
+ GET: async (_req, res, url) => {
2263
+ try {
2264
+ sendJson(res, 200, await worldFiles.dice(url.searchParams.get("id") ?? ""));
2265
+ } catch (error) {
2266
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2267
+ throw error;
2268
+ }
2269
+ },
2270
+ PUT: async (req, res, url) => {
2271
+ try {
2272
+ sendJson(res, 200, await worldFiles.editDice(url.searchParams.get("id") ?? "", parseDiceEdit(await readJsonBody(req))));
2273
+ } catch (error) {
2274
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2275
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2276
+ message: error.message,
2277
+ problems: error.problems
2278
+ });
2279
+ throw error;
2280
+ }
2281
+ }
2282
+ },
2283
+ "/worlds/calendar": {
2284
+ GET: async (_req, res, url) => {
2285
+ try {
2286
+ sendJson(res, 200, await worldFiles.calendar(url.searchParams.get("id") ?? ""));
2287
+ } catch (error) {
2288
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2289
+ throw error;
2290
+ }
2291
+ },
2292
+ PUT: async (req, res, url) => {
2293
+ try {
2294
+ sendJson(res, 200, await worldFiles.editCalendar(url.searchParams.get("id") ?? "", parseCalendarEdit(await readJsonBody(req))));
2295
+ } catch (error) {
2296
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2297
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2298
+ message: error.message,
2299
+ problems: error.problems
2300
+ });
2301
+ throw error;
2302
+ }
2303
+ }
2304
+ },
2069
2305
  "/worlds/variables": {
2070
2306
  GET: async (_req, res, url) => {
2071
2307
  try {
@@ -2374,6 +2610,9 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
2374
2610
  }
2375
2611
  await sendImage(res, image);
2376
2612
  } },
2613
+ "/tools": { GET: async (_req, res) => {
2614
+ sendJson(res, 200, { tools: externalTools?.() ?? [] });
2615
+ } },
2377
2616
  "/sessions/settings": {
2378
2617
  GET: async (_req, res, url) => {
2379
2618
  try {
@@ -2876,7 +3115,8 @@ async function editRoutine(world, key, windows) {
2876
3115
  const parsed = parseCharacterFile(next, folder);
2877
3116
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
2878
3117
  const { locations } = await loadLocations(world.directory);
2879
- const places = routineProblems([parsed.value], locations);
3118
+ const { calendar } = await loadCalendar(world.directory);
3119
+ const places = routineProblems([parsed.value], locations, calendar);
2880
3120
  if (places.length > 0) throw new InvalidEditProblems(places);
2881
3121
  await replaceFile$1(file, next);
2882
3122
  return await readRoutines(world);
@@ -2926,6 +3166,70 @@ async function replaceFileOrCreate(file, text) {
2926
3166
  await writeFile(file, text, { flag: "wx" });
2927
3167
  }
2928
3168
  }
3169
+ /** The calendar of the world as `calendar.json` writes it; a world without one has the northern seasons and no holidays. */
3170
+ async function readCalendarDocument(world) {
3171
+ const { calendar } = await loadCalendar(world.directory);
3172
+ return {
3173
+ hemisphere: calendar.hemisphere,
3174
+ holidays: calendar.holidays.map((holiday) => ({
3175
+ id: holiday.id,
3176
+ name: holiday.name,
3177
+ on: [...holiday.on]
3178
+ }))
3179
+ };
3180
+ }
3181
+ /**
3182
+ * 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.
3183
+ * A calendar with no holidays and the northern seasons is no file at all.
3184
+ * @throws {InvalidEditProblems} naming each problem; nothing is written.
3185
+ */
3186
+ async function editCalendar(world, calendar) {
3187
+ const text = `${JSON.stringify(calendar, null, 2)}\n`;
3188
+ const parsed = parseCalendarFile(text);
3189
+ if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
3190
+ const [{ characters }, { locations }] = await Promise.all([loadCharacters(world.directory), loadLocations(world.directory)]);
3191
+ const problems = routineProblems(characters, locations, parsed.value);
3192
+ const triggers = await readFile(join(world.directory, TRIGGERS_FILE_NAME), "utf8").catch((error) => {
3193
+ if (error.code === "ENOENT") return "";
3194
+ throw error;
3195
+ });
3196
+ const named = new Set(calendar.holidays.map((holiday) => holiday.id));
3197
+ 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`);
3198
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
3199
+ if (calendar.holidays.length === 0 && calendar.hemisphere === "north") await rm(join(world.directory, CALENDAR_FILE_NAME), { force: true });
3200
+ else await replaceFileOrCreate(join(world.directory, CALENDAR_FILE_NAME), text);
3201
+ return await readCalendarDocument(world);
3202
+ }
3203
+ /** The checks of a world as its `dice.json` has them; none without the file. */
3204
+ async function readDiceDocument(world) {
3205
+ const { checks } = await loadDice(world.directory);
3206
+ return { checks };
3207
+ }
3208
+ /**
3209
+ * Replaces the world's checks. They are read as a story start reads them, and a quality of the character that a check adds must be a number the world
3210
+ * declares for characters. No checks is no file at all.
3211
+ * @throws {InvalidEditProblems} naming each problem; nothing is written.
3212
+ */
3213
+ async function editDice(world, dice) {
3214
+ const written = dice.checks.map(({ reading, compare, ...check }) => ({
3215
+ ...check,
3216
+ ...reading === void 0 || reading === "total" ? {} : { reading },
3217
+ ...compare === void 0 || compare === "absolute" ? {} : { compare }
3218
+ }));
3219
+ const text = `${JSON.stringify({ checks: written }, null, 2)}\n`;
3220
+ const parsed = parseDiceFile(text);
3221
+ if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
3222
+ const declared = await loadVariables(world.directory);
3223
+ const problems = parsed.value.flatMap((check) => {
3224
+ if (check.modifier === void 0) return [];
3225
+ const variable = declared.defs.find((def) => def.key === check.modifier);
3226
+ return variable === void 0 || variable.kind !== "number" || variable.subject !== "character" ? [`the check "${check.key}" adds "${check.modifier}", which the world does not declare as a number about characters (Tracked values)`] : [];
3227
+ });
3228
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
3229
+ if (dice.checks.length === 0) await rm(join(world.directory, DICE_FILE_NAME), { force: true });
3230
+ else await replaceFileOrCreate(join(world.directory, DICE_FILE_NAME), text);
3231
+ return await readDiceDocument(world);
3232
+ }
2929
3233
  //#endregion
2930
3234
  //#region src/host/worlds/lore-entries.ts
2931
3235
  const MAX_TITLE = 200;
@@ -3746,6 +4050,10 @@ async function replaceFile(file, text) {
3746
4050
  }
3747
4051
  }
3748
4052
  const textOf = (value) => typeof value === "string" ? value : "";
4053
+ const toolsOf = (value) => {
4054
+ const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
4055
+ return typeof board === "string" ? {} : board;
4056
+ };
3749
4057
  function infoOf(document) {
3750
4058
  const opening = document["opening_message"];
3751
4059
  const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
@@ -3765,6 +4073,7 @@ function infoOf(document) {
3765
4073
  timeZone: textOf(document["time_zone"]),
3766
4074
  startingTime: textOf(document["starting_time"]),
3767
4075
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
4076
+ tools: toolsOf(document["tools"]),
3768
4077
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
3769
4078
  title: textOf(entry["title"]),
3770
4079
  text: entry["text"]
@@ -3827,6 +4136,10 @@ async function editWorldInfo(directory, edit) {
3827
4136
  text: entry.text
3828
4137
  }));
3829
4138
  }
4139
+ if (edit.tools !== void 0) {
4140
+ if (Object.keys(edit.tools).length === 0) delete document["tools"];
4141
+ else document["tools"] = edit.tools;
4142
+ }
3830
4143
  const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
3831
4144
  const parsed = parseWorldFile(next);
3832
4145
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
@@ -3853,7 +4166,7 @@ function worldFindings(session) {
3853
4166
  async function startSession(deps, request) {
3854
4167
  const world = await deps.worlds.find(request.worldId);
3855
4168
  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);
4169
+ const { characters: authored, factions, locations, items, slots, authoredLore, declared, scripted, authoredPlots, calendar, checks } = await loadValidatedWorld(world);
3857
4170
  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
4171
  const opening = request.opening === void 0 ? openingOf(world, authored) : [{
3859
4172
  type: "narration",
@@ -3878,12 +4191,17 @@ async function startSession(deps, request) {
3878
4191
  settings = parsed.value;
3879
4192
  }
3880
4193
  const timeZone = settings.clock.timeZone !== "" ? settings.clock.timeZone : settings.clock.mode === "real" ? systemTimeZone() : world.clock?.timeZone ?? "UTC";
4194
+ const tools = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(world.tools ?? {}), ...Object.keys(settings.tools)])].map((agent) => [agent, {
4195
+ ...world.tools?.[agent],
4196
+ ...settings.tools[agent]
4197
+ }]));
3881
4198
  settings = {
3882
4199
  ...settings,
3883
4200
  clock: {
3884
4201
  ...settings.clock,
3885
4202
  timeZone
3886
- }
4203
+ },
4204
+ tools
3887
4205
  };
3888
4206
  let startsAt = world.clock?.startingTime;
3889
4207
  if (request.startingTime !== void 0 && request.startingTime.trim() !== "") {
@@ -3911,6 +4229,8 @@ async function startSession(deps, request) {
3911
4229
  populateLocations(session, locations);
3912
4230
  populateCharacters(session, characters, player.id);
3913
4231
  populateFactions(session, factions);
4232
+ populateCalendar(session, calendar);
4233
+ populateDice(session, checks);
3914
4234
  populateRoutines(session, characters);
3915
4235
  populateItems(session, items, slots, locations);
3916
4236
  populateLore(session, authoredLore.lore);
@@ -4414,6 +4734,7 @@ async function loadWorld(folder, dir, file, problems) {
4414
4734
  ...world.variables === void 0 ? {} : { variables: world.variables },
4415
4735
  ...world.alternateOpenings === void 0 ? {} : { alternateOpenings: world.alternateOpenings },
4416
4736
  ...world.rules === void 0 ? {} : { rules: world.rules },
4737
+ ...world.tools === void 0 ? {} : { tools: world.tools },
4417
4738
  ...world.narrationVoice === void 0 ? {} : { narrationVoice: world.narrationVoice }
4418
4739
  };
4419
4740
  if (world.coverMediaId !== void 0) try {
@@ -4699,6 +5020,14 @@ function apply(ctx, config) {
4699
5020
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
4700
5021
  return { chatSessionId: await authoring.ensure(world.summary.id, world.summary.name, title, language) };
4701
5022
  },
5023
+ translation: {
5024
+ language: (id) => worldLanguage(worlds, id),
5025
+ start: (id, to, title, language) => startTranslation({
5026
+ worlds,
5027
+ authoring,
5028
+ text: (key, lang, variables) => prompts.text(key, lang, variables)
5029
+ }, id, to, title, language)
5030
+ },
4702
5031
  importer: {
4703
5032
  maxUploadBytes: config.importMaxUploadBytes,
4704
5033
  upload: async (file, name) => {
@@ -4728,6 +5057,10 @@ function apply(ctx, config) {
4728
5057
  return await addAvatarsToWorld(await avatarsWorld(root.path), world, keys, locations);
4729
5058
  }
4730
5059
  },
5060
+ externalTools: () => {
5061
+ const registry = ctx.get("tools");
5062
+ return registry === void 0 ? [] : externalTools(registry);
5063
+ },
4731
5064
  worldFiles: {
4732
5065
  info: async (worldId) => await readWorldInfo((await editableWorld(worlds, worldId, root.path)).directory),
4733
5066
  editInfo: async (worldId, edit) => {
@@ -4737,6 +5070,10 @@ function apply(ctx, config) {
4737
5070
  },
4738
5071
  routines: async (worldId) => await readRoutines(await editableWorld(worlds, worldId, root.path)),
4739
5072
  editRoutine: async (worldId, key, windows) => await editRoutine(await editableWorld(worlds, worldId, root.path), key, windows),
5073
+ dice: async (worldId) => await readDiceDocument(await editableWorld(worlds, worldId, root.path)),
5074
+ editDice: async (worldId, dice) => await editDice(await editableWorld(worlds, worldId, root.path), dice),
5075
+ calendar: async (worldId) => await readCalendarDocument(await editableWorld(worlds, worldId, root.path)),
5076
+ editCalendar: async (worldId, calendar) => await editCalendar(await editableWorld(worlds, worldId, root.path), calendar),
4740
5077
  variables: async (worldId) => await readVariables(await editableWorld(worlds, worldId, root.path)),
4741
5078
  editVariables: async (worldId, declarations) => await editVariables(await editableWorld(worlds, worldId, root.path), declarations),
4742
5079
  prompts: async (worldId, language) => listWorldPrompts((await editableWorld(worlds, worldId, root.path)).directory, language),
@@ -4858,6 +5195,7 @@ function apply(ctx, config) {
4858
5195
  reflect: async (id) => {
4859
5196
  const sessions = join(root.path, "sessions");
4860
5197
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
5198
+ await agent.ensure(id, ctx.roleplayState.openSession(sessions, id).metadata.get().name);
4861
5199
  await ctx.roleplayOrchestration.reflect(chatSessionId(id));
4862
5200
  },
4863
5201
  resetVectors: (id) => {