@dsh-agentic-roleplay/core 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  2. package/lib/authoring.js +193 -227
  3. package/lib/client.js +2710 -1322
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +2 -3
  6. package/lib/deliver-BDW5WZvc.js +2262 -0
  7. package/lib/{documents-Bu5uYRZB.js → documents-DtlY2IRt.js} +958 -10
  8. package/lib/{gallery-DUeBMHQX.js → gallery-DACG5eh2.js} +2 -2
  9. package/lib/{generator-HPifO3Kk.js → generator-DGYcLMp7.js} +2 -2
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +419 -23
  12. package/lib/{narration-BRyHU0H2.js → narration-5ig7Dg28.js} +12 -2
  13. package/lib/orchestration.js +458 -342
  14. package/lib/{packs-ByP1J-zj.js → packs-CkRZDCsV.js} +51 -5
  15. package/lib/{presenter-agent-G43ODV8I.js → presenter-agent-PK9JYExk.js} +4 -4
  16. package/package.json +5 -4
  17. package/packs/scene/map.html +12 -0
  18. package/packs/scene/map.js +55 -0
  19. package/packs/scene/pack.json +11 -0
  20. package/packs/scene/strip.html +11 -0
  21. package/packs/scene/strip.js +26 -0
  22. package/packs/scene/style.css +16 -0
  23. package/prompts/en/roleplay/character-decide.md +1 -1
  24. package/prompts/en/roleplay/character-rules.md +1 -1
  25. package/prompts/en/roleplay/chronicler.md +1 -1
  26. package/prompts/en/roleplay/game-master.md +1 -1
  27. package/prompts/en/roleplay/reflection.md +9 -0
  28. package/prompts/en/roleplay/style.md +1 -1
  29. package/prompts/en/roleplay/suggester.md +1 -1
  30. package/prompts/en/translate/document.md +6 -0
  31. package/prompts/en/translate/glossary.md +5 -0
  32. package/prompts/en/translate/notice.md +2 -0
  33. package/prompts/en/world/procedure.md +1 -1
  34. package/prompts/en/world/welcome.md +1 -1
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-rules.md +1 -1
  37. package/prompts/zh/roleplay/chronicler.md +1 -1
  38. package/prompts/zh/roleplay/game-master.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/roleplay/style.md +1 -1
  41. package/prompts/zh/roleplay/suggester.md +1 -1
  42. package/prompts/zh/translate/document.md +6 -0
  43. package/prompts/zh/translate/glossary.md +5 -0
  44. package/prompts/zh/translate/notice.md +2 -0
  45. package/prompts/zh/world/procedure.md +1 -1
  46. package/prompts/zh/world/welcome.md +1 -1
  47. package/lib/access-C1nFQiyT.js +0 -12
  48. package/lib/activity-t7OBgHlc.js +0 -1386
package/lib/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { n as roleplaySessionOf, t as chatSessionId } from "./chat-AKrVcWIC.js";
2
- import { $ as variableProblems, A as populateCharacters, B as routineProblems, D as markReady, F as populateLocations, G as subfolders, H as loadItems, I as populateLore, J as listWorldPrompts, L as populateRoutines, M as populateFactions, N as populateItems, P as populateKnowledge, Q as parseVariablesFile, R as populateTriggers, U as CHARACTERS_DIR, V as loadLocations, W as loadCharacters, X as writeWorldPrompt, Y as readWorldPrompt, Z as VARIABLES_FILE_NAME, _ as replaceFile$1, at as parseChoices, c as editWorldLore$1, ct as parseWorldInfoEdit, d as editWorldPlots$1, dt as parseFactionEdit, et as CHARACTER_FILE_NAME, f as editWorldRelation$1, ft as parseLoreEdit, g as readWorldEditor, gt as IMPORT_COMMAND, h as generateWorldCharacterPortrait, ht as parseThingEdit, i as readAuthoredEntityDocument, it as ImportStore, j as populateClock, k as loadValidatedWorld, l as editWorldNarrationVoice, lt as InvalidEditProblems, m as entityFolder, mt as parseRelationEdit, n as createAuthoredEntity, nt as IMPORT_FOLDER, o as editWorldCharacter$1, ot as WORLD_FILE_NAME, p as editWorldThing$1, pt as parsePlaceEdit, q as deleteWorldPrompt, r as deleteAuthoredEntity, rt as ImportNotFoundError, s as editWorldFaction$1, st as parseWorldFile, tt as parseCharacterFile, u as editWorldPlace$1, ut as parseCharacterEdit, v as uploadWorldCharacterPortrait, x as authoringChatSessionId, y as worldCharacterPortraitFile, z as populateVariables } from "./documents-Bu5uYRZB.js";
3
- import { A as languageOf, B as SessionNotFoundError, C as errorMessage, D as PromptLibrary, I as AgentUnavailableError, L as InvalidStartError, O as copyWorldPrompts, R as InvalidWorldError, S as readDocument$1, T as formatIssue, V as WorldNotFoundError, _ as API_PREFIX, a as packIds, b as parsePlotsFile, c as describePack, f as readPack, 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 SessionArchivedError } from "./packs-ByP1J-zj.js";
4
- 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-BRyHU0H2.js";
1
+ import { n as chatSessionId, r as roleplaySessionOf } from "./access-EbNdZFbk.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";
5
6
  import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
6
- 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";
7
- import { C as defaultBoundaries, M as zoneOf, S as pathTo, d as plotProgressOf, f as populatePlots, g as notesOfSession, i as readRunDetail, m as addToNote, o as PLOTS_METADATA_KEY, r as readActivity, v as readNotes, x as readTimeline, y as TimelineError } from "./activity-t7OBgHlc.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
- import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
10
+ import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
11
11
  import { createHash, randomBytes, randomUUID } from "node:crypto";
12
12
  import { Session, SessionId } from "@deepseek-ai/dsh-session";
13
13
  import { ToolCallId, createMessage, createSystemMessage, createToolResultMessage } from "@deepseek-ai/dsh-llm";
@@ -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 { 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";
@@ -680,6 +713,10 @@ var RoleplayOrchestration = class extends Service {
680
713
  settle = () => Promise.resolve();
681
714
  /** Stops everything a chat has in flight in the background and waits for it; there while the orchestration is. */
682
715
  halt = () => Promise.resolve();
716
+ /** Starts a reflection of a chat's characters on what they have taken in, in the background; there while the orchestration is. */
717
+ reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
718
+ /** Whether a reflection of the chat is running; there while the orchestration is. */
719
+ reflecting = () => false;
683
720
  /** What the story's turns are and taking the story back to one; there while the orchestration is. */
684
721
  timelines;
685
722
  /** Background scene illustration jobs; there while the orchestration is mounted. */
@@ -707,6 +744,7 @@ var RoleplayOrchestration = class extends Service {
707
744
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
708
745
  const ROUTINE_FIELDS = [
709
746
  "days",
747
+ "on",
710
748
  "from",
711
749
  "to",
712
750
  "activity",
@@ -751,6 +789,7 @@ function parseRoutineEdit(value) {
751
789
  const text = (key) => typeof entry[key] === "string" ? entry[key].trim() : "";
752
790
  return {
753
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 !== "") } : {},
754
793
  from: text("from"),
755
794
  to: text("to"),
756
795
  activity: text("activity"),
@@ -860,6 +899,45 @@ function parseVariablesEdit(value) {
860
899
  if (problems.length > 0) throw new InvalidEditProblems(problems);
861
900
  return declarations;
862
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
+ }
863
941
  //#endregion
864
942
  //#region src/host/worlds/starter.ts
865
943
  const STARTER_FOLDER = "starter-worlds";
@@ -1027,6 +1105,7 @@ const BRIDGE_SCRIPT = `(function () {
1027
1105
  var root = document.documentElement;
1028
1106
  root.setAttribute('data-rp-scheme', data.scheme);
1029
1107
  root.style.colorScheme = data.scheme;
1108
+ if (data.language) root.setAttribute('lang', data.language);
1030
1109
  Object.keys(data.tokens).forEach(function (name) { root.style.setProperty(name, data.tokens[name]); });
1031
1110
  }
1032
1111
  function remove(list, listener) { var index = list.indexOf(listener); if (index >= 0) list.splice(index, 1); }
@@ -1126,10 +1205,14 @@ function playerViewOf(session, options) {
1126
1205
  const clock = session.clock.get();
1127
1206
  if (clock !== void 0) {
1128
1207
  const now = clock.mode === "real" ? options.wall : clock.now;
1208
+ const calendar = readCalendar(session.metadata);
1209
+ const day = addLocalDays(now, options.zone, 0);
1129
1210
  view.time = {
1130
1211
  iso: new Date(now).toISOString(),
1131
1212
  zone: options.zone,
1132
- 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)
1133
1216
  };
1134
1217
  }
1135
1218
  view.variables.push(...shown("the world", shownVariables(session, "world", 0, "world", "others")));
@@ -1234,6 +1317,59 @@ function finish(view, session) {
1234
1317
  };
1235
1318
  }
1236
1319
  //#endregion
1320
+ //#region src/host/interface/preview.ts
1321
+ /** What a story shows for suggestions when a pack is looked at before any story exists. */
1322
+ const SAMPLE_SUGGESTIONS = [
1323
+ "Look around.",
1324
+ "Ask someone here what they know.",
1325
+ "Try the nearest door."
1326
+ ];
1327
+ /**
1328
+ * What a story of this world would show a pack at its start, from the world's files: a story made in memory, the player taking the first
1329
+ * playable character, who then looks around as they do at the start of a turn. Nothing is stored.
1330
+ * @throws {InvalidEditProblems} when the rest of the world has problems of its own.
1331
+ */
1332
+ async function previewViewOf(world, wall) {
1333
+ const parts = await loadWorldParts(world.directory);
1334
+ const player = parts.characters.find((character) => character.role === "playable") ?? parts.characters[0];
1335
+ const scratch = createSessionStore(":memory:", {
1336
+ id: "preview",
1337
+ name: world.summary.name,
1338
+ world: {
1339
+ id: world.summary.id,
1340
+ name: world.summary.name
1341
+ }
1342
+ }, { vectors: false });
1343
+ try {
1344
+ const session = scratch;
1345
+ populateLocations(session, parts.locations);
1346
+ populateCharacters(session, parts.characters, player?.id ?? "");
1347
+ populateItems(session, parts.items, parts.slots, parts.locations);
1348
+ populateKnowledge(session, parts.characters);
1349
+ populateVariables(session, parts.variables, {
1350
+ characters: parts.characters,
1351
+ items: parts.items,
1352
+ locations: parts.locations,
1353
+ values: world.variables
1354
+ });
1355
+ populateClock(session, DEFAULT_SETTINGS.clock, world.clock, wall);
1356
+ observeAsPlayer(session, 1);
1357
+ const view = playerViewOf(session, {
1358
+ zone: world.clock?.timeZone ?? "UTC",
1359
+ wall
1360
+ });
1361
+ const { revision: _, ...rest } = view;
1362
+ return {
1363
+ ...rest,
1364
+ api: 1,
1365
+ suggestions: SAMPLE_SUGGESTIONS,
1366
+ revision: `preview-${view.revision}`
1367
+ };
1368
+ } finally {
1369
+ scratch.close();
1370
+ }
1371
+ }
1372
+ //#endregion
1237
1373
  //#region src/host/interface/storage.ts
1238
1374
  const keyOf$1 = (pack) => `roleplay.interface.${pack}`;
1239
1375
  function checkedKey(key) {
@@ -1286,12 +1422,16 @@ var InvalidPacksError = class extends Error {
1286
1422
  this.problems = problems;
1287
1423
  }
1288
1424
  };
1425
+ /** What stands for a pack looked at in the editor where a session id would be; the key after it is the frame's. */
1426
+ const PREVIEW = "preview:";
1289
1427
  const addressFor = (session) => (path) => `roleplay-api/sessions/interface/pack/${session}/${path.split("/").map(encodeURIComponent).join("/")}`;
1290
1428
  /** What the interface packs of the stories show and do, for the browser. */
1291
1429
  var InterfaceService = class {
1292
1430
  deps;
1293
1431
  keys = /* @__PURE__ */ new Map();
1294
1432
  keyOf = /* @__PURE__ */ new Map();
1433
+ /** The pack folders being previewed, by frame key. */
1434
+ previews = /* @__PURE__ */ new Map();
1295
1435
  constructor(deps) {
1296
1436
  this.deps = deps;
1297
1437
  }
@@ -1311,6 +1451,73 @@ var InterfaceService = class {
1311
1451
  sessions() {
1312
1452
  return join(this.deps.root(), "sessions");
1313
1453
  }
1454
+ async worldOf(worldId) {
1455
+ const world = await this.deps.world(worldId);
1456
+ if (world === void 0) throw new WorldNotFoundError(`there is no world "${worldId}"`);
1457
+ return world;
1458
+ }
1459
+ /** The packs of a world, each with what it holds and what is wrong with it. @throws {WorldNotFoundError} */
1460
+ async worldPacks(worldId) {
1461
+ const { directory } = await this.worldOf(worldId);
1462
+ return packIds(directory).map((id) => {
1463
+ const { pack, problems } = readPack(join(directory, "ui", id), id, (file) => file);
1464
+ if (pack === void 0) return {
1465
+ id,
1466
+ name: id,
1467
+ version: "",
1468
+ description: "",
1469
+ actions: [],
1470
+ surfaces: {},
1471
+ tokens: 0,
1472
+ files: [],
1473
+ problems
1474
+ };
1475
+ const { manifest } = pack;
1476
+ return {
1477
+ id,
1478
+ name: manifest.name,
1479
+ version: manifest.version,
1480
+ description: manifest.description,
1481
+ actions: manifest.actions,
1482
+ surfaces: manifest.surfaces,
1483
+ ...manifest.skin === void 0 ? {} : { skin: manifest.skin },
1484
+ tokens: Object.keys(manifest.theme).length,
1485
+ files: [...pack.files].map(([path, file]) => ({
1486
+ path,
1487
+ size: file.size
1488
+ })),
1489
+ problems
1490
+ };
1491
+ });
1492
+ }
1493
+ /**
1494
+ * A pack of a world as a story of that world would start with it: its surfaces load their own files, and are given the view the story would show.
1495
+ * @throws {WorldNotFoundError} when the world, or the pack in it, is not there.
1496
+ * @throws {InvalidPacksError} when the pack has problems.
1497
+ * @throws {InvalidEditProblems} when the rest of the world has problems of its own.
1498
+ */
1499
+ async preview(worldId, packId) {
1500
+ const world = await this.worldOf(worldId);
1501
+ const folder = join(world.directory, "ui", packId);
1502
+ if (!isPackId(packId) || !existsSync(folder)) throw new WorldNotFoundError(`the world carries no pack "${packId}"`);
1503
+ const name = `${worldId}\n${packId}`;
1504
+ const key = this.keyOf.get(`${PREVIEW}${name}`) ?? randomBytes(24).toString("base64url");
1505
+ const { pack, problems } = readPack(folder, packId, addressFor(`${PREVIEW}${key}`));
1506
+ if (pack === void 0) throw new InvalidPacksError(`the pack "${packId}" has ${problems.length} problem(s)`, problems.map((problem) => ({
1507
+ path: problem.file,
1508
+ message: problem.message
1509
+ })));
1510
+ this.keyOf.set(`${PREVIEW}${name}`, key);
1511
+ this.keys.set(key, `${PREVIEW}${key}`);
1512
+ this.previews.set(key, {
1513
+ folder,
1514
+ pack: packId
1515
+ });
1516
+ return {
1517
+ pack: describePack(pack, key),
1518
+ view: await previewViewOf(world, (this.deps.wall ?? Date.now)())
1519
+ };
1520
+ }
1314
1521
  session(id) {
1315
1522
  if (!isSessionId(id) || !existsSync(sessionDatabase(this.sessions(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1316
1523
  return {
@@ -1412,7 +1619,7 @@ var InterfaceService = class {
1412
1619
  }
1413
1620
  /** A file of the session's pack; a page of it comes with the bridge. @returns nothing when the pack has no such file. */
1414
1621
  file(id, path) {
1415
- const { pack } = this.active(id);
1622
+ const pack = id.startsWith(PREVIEW) ? this.previewed(id) : this.active(id).pack;
1416
1623
  const found = pack === void 0 ? void 0 : packFile(pack, path);
1417
1624
  if (found === void 0) return void 0;
1418
1625
  return found.mediaType.startsWith("text/html") ? {
@@ -1424,6 +1631,11 @@ var InterfaceService = class {
1424
1631
  ...found
1425
1632
  };
1426
1633
  }
1634
+ /** The pack of a preview, read afresh. */
1635
+ previewed(id) {
1636
+ const shown = this.previews.get(id.slice(8));
1637
+ return shown === void 0 ? void 0 : readPack(shown.folder, shown.pack, addressFor(id)).pack;
1638
+ }
1427
1639
  /** What the pack keeps in the session. @throws {RangeError} when a value does not fit. */
1428
1640
  storage(id, request) {
1429
1641
  const { session } = this.session(id);
@@ -1522,6 +1734,28 @@ function interfaceRoutes(api) {
1522
1734
  notFound(res, error);
1523
1735
  }
1524
1736
  } },
1737
+ "/worlds/interface": { GET: async (_req, res, url) => {
1738
+ try {
1739
+ sendJson(res, 200, await api.worldPacks(url.searchParams.get("id") ?? ""));
1740
+ } catch (error) {
1741
+ notFound(res, error);
1742
+ }
1743
+ } },
1744
+ "/worlds/interface/preview": { GET: async (_req, res, url) => {
1745
+ try {
1746
+ sendJson(res, 200, await api.preview(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? ""));
1747
+ } catch (error) {
1748
+ if (error instanceof InvalidPacksError) return sendJson(res, 422, {
1749
+ message: error.message,
1750
+ problems: error.problems.map((problem) => `${problem.path === "" ? "" : `${problem.path}: `}${problem.message}`)
1751
+ });
1752
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
1753
+ message: error.message,
1754
+ problems: error.problems
1755
+ });
1756
+ notFound(res, error);
1757
+ }
1758
+ } },
1525
1759
  "/interface/availability": { GET: async (_req, res) => {
1526
1760
  sendJson(res, 200, api.availability());
1527
1761
  } }
@@ -1608,7 +1842,7 @@ function languageField(value) {
1608
1842
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
1609
1843
  }
1610
1844
  }
1611
- 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 }) {
1612
1846
  const routes = {
1613
1847
  "/speech/capabilities": { GET: async (_req, res) => {
1614
1848
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1727,6 +1961,30 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
1727
1961
  throw error;
1728
1962
  }
1729
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
+ } },
1730
1988
  "/avatars": {
1731
1989
  POST: async (req, res) => {
1732
1990
  const body = await readJsonBody(req);
@@ -1910,6 +2168,28 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
1910
2168
  throw error;
1911
2169
  }
1912
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
+ },
1913
2193
  "/worlds/variables": {
1914
2194
  GET: async (_req, res, url) => {
1915
2195
  try {
@@ -2409,6 +2689,17 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
2409
2689
  throw error;
2410
2690
  }
2411
2691
  } },
2692
+ "/sessions/reflect": { POST: async (_req, res, url) => {
2693
+ try {
2694
+ await sessions.reflect(url.searchParams.get("id") ?? "");
2695
+ } catch (error) {
2696
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2697
+ if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
2698
+ throw error;
2699
+ }
2700
+ res.statusCode = 202;
2701
+ res.end();
2702
+ } },
2412
2703
  "/sessions/vectors/reset": { POST: async (_req, res, url) => {
2413
2704
  try {
2414
2705
  sessions.resetVectors(url.searchParams.get("id") ?? "");
@@ -2709,7 +3000,8 @@ async function editRoutine(world, key, windows) {
2709
3000
  const parsed = parseCharacterFile(next, folder);
2710
3001
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
2711
3002
  const { locations } = await loadLocations(world.directory);
2712
- const places = routineProblems([parsed.value], locations);
3003
+ const { calendar } = await loadCalendar(world.directory);
3004
+ const places = routineProblems([parsed.value], locations, calendar);
2713
3005
  if (places.length > 0) throw new InvalidEditProblems(places);
2714
3006
  await replaceFile$1(file, next);
2715
3007
  return await readRoutines(world);
@@ -2759,6 +3051,40 @@ async function replaceFileOrCreate(file, text) {
2759
3051
  await writeFile(file, text, { flag: "wx" });
2760
3052
  }
2761
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
+ }
2762
3088
  //#endregion
2763
3089
  //#region src/host/worlds/lore-entries.ts
2764
3090
  const MAX_TITLE = 200;
@@ -3063,6 +3389,22 @@ function worldOf(session, sessionsDir) {
3063
3389
  definition: plot,
3064
3390
  progress
3065
3391
  }));
3392
+ const triggers = session.triggers.list().map((trigger) => ({
3393
+ key: trigger.key,
3394
+ name: trigger.name,
3395
+ when: trigger.condition,
3396
+ effects: trigger.effects,
3397
+ repeat: trigger.repeat,
3398
+ priority: trigger.priority,
3399
+ ...trigger.cooldownSeconds === void 0 ? {} : { cooldownSeconds: trigger.cooldownSeconds },
3400
+ ...trigger.chance === void 0 ? {} : { chance: trigger.chance },
3401
+ ...trigger.expires === void 0 ? {} : { expires: trigger.expires },
3402
+ announced: trigger.announce !== void 0,
3403
+ status: trigger.status,
3404
+ fireCount: trigger.fireCount,
3405
+ origin: trigger.origin,
3406
+ problems: trigger.problem === void 0 ? [] : [trigger.problem]
3407
+ }));
3066
3408
  return {
3067
3409
  ...typeof narrationVoice === "string" ? { narrationVoice } : {},
3068
3410
  characters,
@@ -3070,6 +3412,7 @@ function worldOf(session, sessionsDir) {
3070
3412
  things,
3071
3413
  factions,
3072
3414
  lore,
3415
+ triggers,
3073
3416
  plots,
3074
3417
  relations
3075
3418
  };
@@ -3669,7 +4012,7 @@ function worldFindings(session) {
3669
4012
  async function startSession(deps, request) {
3670
4013
  const world = await deps.worlds.find(request.worldId);
3671
4014
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
3672
- 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);
3673
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)}`);
3674
4017
  const opening = request.opening === void 0 ? openingOf(world, authored) : [{
3675
4018
  type: "narration",
@@ -3727,6 +4070,7 @@ async function startSession(deps, request) {
3727
4070
  populateLocations(session, locations);
3728
4071
  populateCharacters(session, characters, player.id);
3729
4072
  populateFactions(session, factions);
4073
+ populateCalendar(session, calendar);
3730
4074
  populateRoutines(session, characters);
3731
4075
  populateItems(session, items, slots, locations);
3732
4076
  populateLore(session, authoredLore.lore);
@@ -3896,10 +4240,39 @@ function payloadOf(deps, id, settings) {
3896
4240
  activity: deps.activity(id),
3897
4241
  interventions: deps.interventions(id),
3898
4242
  vectors: deps.vectors(id),
4243
+ reflection: deps.reflection(id),
3899
4244
  ...clockMode === void 0 ? {} : { clockMode }
3900
4245
  };
3901
4246
  }
3902
4247
  //#endregion
4248
+ //#region src/host/interface/first-party.ts
4249
+ /** The folder of the packs shipped with the package. */
4250
+ const FIRST_PARTY_FOLDER = "packs";
4251
+ /** Found from this module, so that it works from source and from the build. */
4252
+ function firstPartyDirectory(from = dirname(fileURLToPath(import.meta.url))) {
4253
+ for (let directory = from;; directory = dirname(directory)) {
4254
+ const candidate = join(directory, FIRST_PARTY_FOLDER);
4255
+ if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
4256
+ if (dirname(directory) === directory) throw new Error("the interface packs shipped with the package were not found");
4257
+ }
4258
+ }
4259
+ /**
4260
+ * Puts the packs that ship with the package into the roleplay root's own `ui` folder, where any story can use one by naming it. A pack
4261
+ * that is there is never overwritten, so it can be edited; one that was deleted comes back.
4262
+ * @returns the packs that were put there.
4263
+ */
4264
+ function installFirstPartyPacks(root, shipped = firstPartyDirectory()) {
4265
+ const installed = [];
4266
+ for (const entry of readdirSync(shipped, { withFileTypes: true })) {
4267
+ if (!entry.isDirectory() || !isPackId(entry.name)) continue;
4268
+ const target = join(root, "ui", entry.name);
4269
+ if (existsSync(target)) continue;
4270
+ cpSync(join(shipped, entry.name), target, { recursive: true });
4271
+ installed.push(entry.name);
4272
+ }
4273
+ return installed;
4274
+ }
4275
+ //#endregion
3903
4276
  //#region src/host/sessions/vectors.ts
3904
4277
  /** How many waiting texts are counted before saying "that many": the number is for reassurance, not accounting. */
3905
4278
  const MAX_COUNTED = 1e4;
@@ -3926,14 +4299,19 @@ function resetVectors(session) {
3926
4299
  //#region src/host/sessions/interventions.ts
3927
4300
  /** What the story's triggers delivered lately and what became of each, oldest first. */
3928
4301
  function readInterventions(session) {
3929
- return session.triggers.notes().slice(-30).map((note) => ({
3930
- turn: note.turn,
3931
- kind: note.kind,
3932
- text: note.text,
3933
- trigger: session.triggers.get(note.triggerId)?.key ?? "",
3934
- characters: note.characterIds.flatMap((id) => session.characters.get(id)?.name ?? []),
3935
- status: note.status === "pending" ? "waiting" : note.status === "done" ? "taken" : "lapsed"
3936
- }));
4302
+ const withdrawn = readWithdrawn(session);
4303
+ return session.triggers.notes().slice(-30).map((note) => {
4304
+ const reason = note.status === "lapsed" ? withdrawn[note.id] : void 0;
4305
+ return {
4306
+ turn: note.turn,
4307
+ kind: note.kind,
4308
+ text: note.text,
4309
+ trigger: session.triggers.get(note.triggerId)?.key ?? "",
4310
+ characters: note.characterIds.flatMap((id) => session.characters.get(id)?.name ?? []),
4311
+ status: note.status === "pending" ? "waiting" : note.status === "done" ? "taken" : reason === void 0 ? "lapsed" : "withdrawn",
4312
+ ...reason === void 0 ? {} : { reason }
4313
+ };
4314
+ });
3937
4315
  }
3938
4316
  //#endregion
3939
4317
  //#region src/host/sessions/open-session.ts
@@ -4428,6 +4806,7 @@ function apply(ctx, config) {
4428
4806
  const worlds = new WorldCatalog(ctx, root);
4429
4807
  const prompts = new PromptLibrary(ctx, root);
4430
4808
  prompts.bootstrap();
4809
+ installFirstPartyPacks(root.path);
4431
4810
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
4432
4811
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
4433
4812
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
@@ -4445,6 +4824,7 @@ function apply(ctx, config) {
4445
4824
  clockMode: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).clock.get()?.mode,
4446
4825
  pendingConsolidation: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).consolidation.pending().length,
4447
4826
  vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4827
+ reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), ctx.roleplayOrchestration.reflecting(chatSessionId(id))),
4448
4828
  activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4449
4829
  interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
4450
4830
  };
@@ -4460,7 +4840,8 @@ function apply(ctx, config) {
4460
4840
  packs: new InterfaceService({
4461
4841
  open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
4462
4842
  root: () => root.path,
4463
- worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory
4843
+ worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory,
4844
+ world: (worldId) => worlds.find(worldId)
4464
4845
  }),
4465
4846
  speech: {
4466
4847
  voices: async () => await voicesOf(textToSpeechOf(ctx)),
@@ -4478,6 +4859,14 @@ function apply(ctx, config) {
4478
4859
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
4479
4860
  return { chatSessionId: await authoring.ensure(world.summary.id, world.summary.name, title, language) };
4480
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
+ },
4481
4870
  importer: {
4482
4871
  maxUploadBytes: config.importMaxUploadBytes,
4483
4872
  upload: async (file, name) => {
@@ -4516,6 +4905,8 @@ function apply(ctx, config) {
4516
4905
  },
4517
4906
  routines: async (worldId) => await readRoutines(await editableWorld(worlds, worldId, root.path)),
4518
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),
4519
4910
  variables: async (worldId) => await readVariables(await editableWorld(worlds, worldId, root.path)),
4520
4911
  editVariables: async (worldId, declarations) => await editVariables(await editableWorld(worlds, worldId, root.path), declarations),
4521
4912
  prompts: async (worldId, language) => listWorldPrompts((await editableWorld(worlds, worldId, root.path)).directory, language),
@@ -4634,6 +5025,11 @@ function apply(ctx, config) {
4634
5025
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
4635
5026
  return readRunDetail(sessionFolder(sessions, id), run);
4636
5027
  },
5028
+ reflect: async (id) => {
5029
+ const sessions = join(root.path, "sessions");
5030
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
5031
+ await ctx.roleplayOrchestration.reflect(chatSessionId(id));
5032
+ },
4637
5033
  resetVectors: (id) => {
4638
5034
  const sessions = join(root.path, "sessions");
4639
5035
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);