@dsh-agentic-roleplay/core 0.1.1 → 0.3.0

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 (52) hide show
  1. package/README.md +1 -1
  2. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  3. package/lib/authoring.js +469 -17
  4. package/lib/client.js +3013 -607
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +2 -3
  7. package/lib/{activity-BbqFG9-3.js → deliver--uMhC6oO.js} +741 -55
  8. package/lib/{documents-ZVoUTnD2.js → documents-7GMc5NnW.js} +108 -5
  9. package/lib/{gallery-KGCdeCnM.js → gallery-DUeBMHQX.js} +2 -2
  10. package/lib/{generator-NYnNdpWb.js → generator-HPifO3Kk.js} +125 -20
  11. package/lib/images.js +3 -3
  12. package/lib/index.js +865 -15
  13. package/lib/{narration-DcnCqA1l.js → narration-CKZTk5UE.js} +19 -4
  14. package/lib/orchestration.js +373 -207
  15. package/lib/packs-alJTiDM2.js +1336 -0
  16. package/lib/{presenter-agent-7j1c7QEz.js → presenter-agent-PX1WVaJB.js} +4 -4
  17. package/package.json +5 -3
  18. package/packs/scene/map.html +12 -0
  19. package/packs/scene/map.js +55 -0
  20. package/packs/scene/pack.json +11 -0
  21. package/packs/scene/strip.html +11 -0
  22. package/packs/scene/strip.js +26 -0
  23. package/packs/scene/style.css +16 -0
  24. package/prompts/en/roleplay/ask-answerer.md +3 -0
  25. package/prompts/en/roleplay/ask-question.md +2 -0
  26. package/prompts/en/roleplay/character-decide.md +1 -1
  27. package/prompts/en/roleplay/character-lookup.md +1 -1
  28. package/prompts/en/roleplay/game-master.md +5 -1
  29. package/prompts/en/roleplay/ooc-empty.md +1 -1
  30. package/prompts/en/roleplay/reflection.md +9 -0
  31. package/prompts/en/world/procedure.md +1 -1
  32. package/prompts/en/world/welcome.md +1 -1
  33. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  34. package/prompts/zh/roleplay/ask-question.md +2 -0
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-lookup.md +1 -1
  37. package/prompts/zh/roleplay/game-master.md +5 -1
  38. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/world/procedure.md +1 -1
  41. package/prompts/zh/world/welcome.md +1 -1
  42. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  43. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  44. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  45. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  46. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  47. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  48. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  49. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  50. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  51. package/lib/access-C1nFQiyT.js +0 -12
  52. package/lib/worlds-DYgjdH8O.js +0 -504
package/lib/index.js CHANGED
@@ -1,14 +1,14 @@
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-ZVoUTnD2.js";
3
- import { C as SessionArchivedError, S as InvalidWorldError, T as WorldNotFoundError, a as plotReferenceProblems, b as AgentUnavailableError, d as PromptLibrary, f as copyWorldPrompts, i as parsePlotsFile, l as formatIssue, m as languageOf, o as readDocument$1, s as errorMessage, t as API_PREFIX, w as SessionNotFoundError, x as InvalidStartError } from "./worlds-DYgjdH8O.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-DcnCqA1l.js";
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";
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-NYnNdpWb.js";
7
- import { a as notesOfSession, c as PLOTS_METADATA_KEY, g as TimelineError, m as populatePlots, p as plotProgressOf, r as addToNote, t as readActivity, v as defaultBoundaries } from "./activity-BbqFG9-3.js";
8
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-KGCdeCnM.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";
9
9
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
10
- import { createReadStream, existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
11
- import { randomUUID } from "node:crypto";
10
+ import { cpSync, createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from "node:fs";
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";
14
14
  import { setApprovalPolicy } from "@deepseek-ai/dsh-user-approval";
@@ -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 { isSessionId, lintWorld, parseInstant, sessionDatabase, sessionFolder, systemTimeZone } from "@dsh-agentic-roleplay/state";
19
+ import { createSessionStore, describeInstant, describeValue, isSessionId, itemKey, lintWorld, locationKey, parseInstant, 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";
@@ -680,6 +680,10 @@ var RoleplayOrchestration = class extends Service {
680
680
  settle = () => Promise.resolve();
681
681
  /** Stops everything a chat has in flight in the background and waits for it; there while the orchestration is. */
682
682
  halt = () => Promise.resolve();
683
+ /** Starts a reflection of a chat's characters on what they have taken in, in the background; there while the orchestration is. */
684
+ reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
685
+ /** Whether a reflection of the chat is running; there while the orchestration is. */
686
+ reflecting = () => false;
683
687
  /** What the story's turns are and taking the story back to one; there while the orchestration is. */
684
688
  timelines;
685
689
  /** Background scene illustration jobs; there while the orchestration is mounted. */
@@ -982,6 +986,733 @@ async function readBinaryBody(req, limit) {
982
986
  if (size === 0) throw new HttpError(400, "the upload is empty");
983
987
  return Buffer.concat(chunks);
984
988
  }
989
+ /** The headers of every file of a pack. */
990
+ const PACK_HEADERS = {
991
+ "content-security-policy": [
992
+ "sandbox allow-scripts",
993
+ "default-src 'none'",
994
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'",
995
+ "worker-src 'self' blob:",
996
+ "style-src 'self' 'unsafe-inline'",
997
+ "img-src 'self' data: blob:",
998
+ "font-src 'self' data:",
999
+ "media-src 'self' data: blob:",
1000
+ "connect-src 'self'",
1001
+ "frame-src 'self'",
1002
+ "form-action 'none'",
1003
+ "base-uri 'self'"
1004
+ ].join("; "),
1005
+ "x-content-type-options": "nosniff",
1006
+ "cache-control": "no-cache",
1007
+ "referrer-policy": "no-referrer"
1008
+ };
1009
+ /**
1010
+ * The `rp` object a surface sees. It is plain ES5 so that it runs wherever the page does, and it only
1011
+ * posts messages: every decision is the page's. Requests time out after 20 seconds.
1012
+ */
1013
+ const BRIDGE_SCRIPT = `(function () {
1014
+ var API = 1;
1015
+ var pending = {};
1016
+ var counter = 0;
1017
+ var watchers = [];
1018
+ var listeners = { turn: [], suggestions: [], theme: [] };
1019
+ var latest;
1020
+ function post(message) { message.rp = API; parent.postMessage(message, '*'); }
1021
+ function request(method, params) {
1022
+ return new Promise(function (resolve, reject) {
1023
+ var id = ++counter;
1024
+ var timer = setTimeout(function () { delete pending[id]; reject(new Error('rp.' + method + ' did not get an answer')); }, 20000);
1025
+ pending[id] = { resolve: resolve, reject: reject, timer: timer };
1026
+ post({ type: 'request', id: id, method: method, params: params });
1027
+ });
1028
+ }
1029
+ function each(list, value) { list.slice().forEach(function (listener) { try { listener(value); } catch (error) { console.error(error); } }); }
1030
+ function applyTheme(data) {
1031
+ var root = document.documentElement;
1032
+ root.setAttribute('data-rp-scheme', data.scheme);
1033
+ root.style.colorScheme = data.scheme;
1034
+ if (data.language) root.setAttribute('lang', data.language);
1035
+ Object.keys(data.tokens).forEach(function (name) { root.style.setProperty(name, data.tokens[name]); });
1036
+ }
1037
+ function remove(list, listener) { var index = list.indexOf(listener); if (index >= 0) list.splice(index, 1); }
1038
+ window.addEventListener('message', function (event) {
1039
+ if (event.source !== parent) return;
1040
+ var message = event.data;
1041
+ if (!message || message.rp !== API) return;
1042
+ if (message.type === 'response') {
1043
+ var entry = pending[message.id];
1044
+ if (!entry) return;
1045
+ delete pending[message.id];
1046
+ clearTimeout(entry.timer);
1047
+ if (message.ok) entry.resolve(message.value); else entry.reject(new Error(message.error));
1048
+ } else if (message.type === 'event') {
1049
+ if (message.name === 'state') { latest = message.data; each(watchers, latest); }
1050
+ else if (message.name === 'theme') { applyTheme(message.data); each(listeners.theme, message.data); }
1051
+ else if (listeners[message.name]) each(listeners[message.name], message.data);
1052
+ }
1053
+ });
1054
+ function on(name, listener) {
1055
+ if (!listeners[name]) throw new Error('rp.on: there is no event "' + name + '"');
1056
+ listeners[name].push(listener);
1057
+ return function () { remove(listeners[name], listener); };
1058
+ }
1059
+ window.rp = Object.freeze({
1060
+ api: API,
1061
+ state: function () { return latest ? Promise.resolve(latest) : request('state'); },
1062
+ watch: function (listener) {
1063
+ watchers.push(listener);
1064
+ if (latest) listener(latest);
1065
+ return function () { remove(watchers, listener); };
1066
+ },
1067
+ on: on,
1068
+ say: function (text) { return request('say', { text: String(text) }); },
1069
+ fill: function (text) { return request('fill', { text: String(text) }); },
1070
+ choose: function (index) { return request('choose', { index: index }); },
1071
+ storage: {
1072
+ get: function (key) { return request('storage.get', { key: String(key) }); },
1073
+ set: function (key, value) { return request('storage.set', { key: String(key), value: value }); },
1074
+ remove: function (key) { return request('storage.remove', { key: String(key) }); }
1075
+ },
1076
+ history: function (limit) { return request('history', { limit: limit }); },
1077
+ open: function (surface) { return request('open', { surface: String(surface) }); },
1078
+ resize: function (height) { post({ type: 'resize', height: Number(height) }); },
1079
+ theme: function () { return request('theme'); }
1080
+ });
1081
+ post({ type: 'hello' });
1082
+ })();`;
1083
+ /**
1084
+ * A surface's HTML with the bridge put first, so that `rp` exists before any script of the pack runs.
1085
+ * It goes right after the opening of `<head>`, else of `<html>`, else at the top (never before a doctype).
1086
+ */
1087
+ function withBridge(html) {
1088
+ const script = `<script>${BRIDGE_SCRIPT}<\/script>`;
1089
+ for (const opening of [
1090
+ /<head(\s[^>]*)?>/i,
1091
+ /<html(\s[^>]*)?>/i,
1092
+ /<!doctype[^>]*>/i
1093
+ ]) {
1094
+ const match = opening.exec(html);
1095
+ if (match !== null) return `${html.slice(0, match.index + match[0].length)}${script}${html.slice(match.index + match[0].length)}`;
1096
+ }
1097
+ return `${script}${html}`;
1098
+ }
1099
+ //#endregion
1100
+ //#region src/host/interface/player-view.ts
1101
+ const keyOf$2 = (character) => character.sourceId ?? String(character.id);
1102
+ /** What a variable shows, in one line of data. */
1103
+ function shown(subject, entries) {
1104
+ return entries.map(({ variable, value }) => ({
1105
+ subject,
1106
+ name: variable.name,
1107
+ value: describeValue(variable, value)
1108
+ }));
1109
+ }
1110
+ /**
1111
+ * What the player may know of the story, for an interface pack to show. It is built field by field from what a person at the
1112
+ * player's character's side could see: nothing private, hidden or unknown is read, so nothing of it can leave through here.
1113
+ */
1114
+ function playerViewOf(session, options) {
1115
+ const metadata = session.metadata.get();
1116
+ const player = session.characters.list().find((character) => character.control === "player");
1117
+ const view = {
1118
+ api: 1,
1119
+ story: {
1120
+ name: metadata.name,
1121
+ turn: metadata.turns
1122
+ },
1123
+ map: {
1124
+ places: [],
1125
+ routes: []
1126
+ },
1127
+ carried: [],
1128
+ variables: [],
1129
+ suggestions: []
1130
+ };
1131
+ const clock = session.clock.get();
1132
+ if (clock !== void 0) {
1133
+ const now = clock.mode === "real" ? options.wall : clock.now;
1134
+ view.time = {
1135
+ iso: new Date(now).toISOString(),
1136
+ zone: options.zone,
1137
+ text: describeInstant(now, options.zone)
1138
+ };
1139
+ }
1140
+ view.variables.push(...shown("the world", shownVariables(session, "world", 0, "world", "others")));
1141
+ if (player === void 0) return finish(view, session);
1142
+ const playerState = session.characterStates.get(player.id);
1143
+ view.player = {
1144
+ key: keyOf$2(player),
1145
+ name: player.name,
1146
+ summary: player.summary,
1147
+ publicState: playerState?.publicState ?? ""
1148
+ };
1149
+ view.variables.push(...shown(player.name, shownVariables(session, "character", player.id, keyOf$2(player), "others")));
1150
+ const placement = session.placements.get("character", player.id);
1151
+ const here = placement === void 0 ? void 0 : session.locations.get(placement.locationId);
1152
+ const known = new Set(session.knowledge.list(player.id, "location").map((entry) => entry.subjectId));
1153
+ if (here !== void 0) {
1154
+ known.add(here.id);
1155
+ view.place = {
1156
+ key: locationKey(here),
1157
+ name: here.name,
1158
+ description: here.description,
1159
+ features: here.features.map((feature) => ({
1160
+ key: feature.key,
1161
+ name: feature.name
1162
+ })),
1163
+ exits: session.locations.exitsFrom(here.id).flatMap((exit) => {
1164
+ const to = known.has(exit.toId) ? session.locations.get(exit.toId) : void 0;
1165
+ return to === void 0 ? [] : [{
1166
+ name: to.name,
1167
+ open: exit.state === "open"
1168
+ }];
1169
+ }),
1170
+ items: session.items.contents({
1171
+ kind: "location",
1172
+ id: here.id
1173
+ }).filter((entry) => !entry.item.hidden).map((entry) => ({
1174
+ name: entry.item.name,
1175
+ quantity: entry.item.quantity
1176
+ })),
1177
+ here: session.placements.at(here.id, "character").flatMap((other) => {
1178
+ const character = other.entityId === player.id ? void 0 : session.characters.get(other.entityId);
1179
+ return character === void 0 ? [] : [{
1180
+ key: keyOf$2(character),
1181
+ name: character.name,
1182
+ publicState: session.characterStates.get(character.id)?.publicState ?? ""
1183
+ }];
1184
+ })
1185
+ };
1186
+ view.variables.push(...shown(here.name, shownVariables(session, "location", here.id, locationKey(here), "others")));
1187
+ for (const other of view.place.here) {
1188
+ const character = session.characters.list().find((candidate) => keyOf$2(candidate) === other.key);
1189
+ if (character !== void 0) view.variables.push(...shown(character.name, shownVariables(session, "character", character.id, other.key, "others")));
1190
+ }
1191
+ for (const entry of session.items.contents({
1192
+ kind: "location",
1193
+ id: here.id
1194
+ }).filter((candidate) => !candidate.item.hidden)) view.variables.push(...shown(entry.item.name, shownVariables(session, "item", entry.item.id, itemKey(entry.item), "others")));
1195
+ }
1196
+ view.carried = session.items.contents({
1197
+ kind: "character",
1198
+ id: player.id
1199
+ }).filter((entry) => !entry.item.hidden).map((entry) => {
1200
+ const holder = entry.holding.holder;
1201
+ return {
1202
+ name: entry.item.name,
1203
+ quantity: entry.item.quantity,
1204
+ where: holder.kind === "character" && holder.mode === "worn" ? `worn on the ${holder.slot}` : "carried"
1205
+ };
1206
+ });
1207
+ const places = [...known].flatMap((id) => {
1208
+ const place = session.locations.get(id);
1209
+ return place === void 0 ? [] : [place];
1210
+ });
1211
+ view.map.places = places.map((place) => ({
1212
+ key: locationKey(place),
1213
+ name: place.name,
1214
+ ...parentKey(session, place.parentId, known) === void 0 ? {} : { parent: parentKey(session, place.parentId, known) },
1215
+ here: place.id === here?.id
1216
+ }));
1217
+ const exits = session.locations.allExits();
1218
+ view.map.routes = session.knowledge.list(player.id, "exit").flatMap((entry) => {
1219
+ const exit = exits.find((candidate) => candidate.id === entry.subjectId);
1220
+ const from = exit === void 0 ? void 0 : session.locations.get(exit.fromId);
1221
+ const to = exit === void 0 ? void 0 : session.locations.get(exit.toId);
1222
+ return from === void 0 || to === void 0 || !known.has(from.id) || !known.has(to.id) ? [] : [{
1223
+ from: locationKey(from),
1224
+ to: locationKey(to)
1225
+ }];
1226
+ });
1227
+ return finish(view, session);
1228
+ }
1229
+ function parentKey(session, parentId, known) {
1230
+ const parent = parentId === void 0 || !known.has(parentId) ? void 0 : session.locations.get(parentId);
1231
+ return parent === void 0 ? void 0 : locationKey(parent);
1232
+ }
1233
+ function finish(view, session) {
1234
+ view.suggestions = readNotes(session).find((note) => note.kind === "suggestions")?.lines ?? [];
1235
+ const revision = createHash("sha256").update(JSON.stringify(view)).digest("hex").slice(0, 16);
1236
+ return {
1237
+ ...view,
1238
+ revision
1239
+ };
1240
+ }
1241
+ //#endregion
1242
+ //#region src/host/interface/preview.ts
1243
+ /** What a story shows for suggestions when a pack is looked at before any story exists. */
1244
+ const SAMPLE_SUGGESTIONS = [
1245
+ "Look around.",
1246
+ "Ask someone here what they know.",
1247
+ "Try the nearest door."
1248
+ ];
1249
+ /**
1250
+ * 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
1251
+ * playable character, who then looks around as they do at the start of a turn. Nothing is stored.
1252
+ * @throws {InvalidEditProblems} when the rest of the world has problems of its own.
1253
+ */
1254
+ async function previewViewOf(world, wall) {
1255
+ const parts = await loadWorldParts(world.directory);
1256
+ const player = parts.characters.find((character) => character.role === "playable") ?? parts.characters[0];
1257
+ const scratch = createSessionStore(":memory:", {
1258
+ id: "preview",
1259
+ name: world.summary.name,
1260
+ world: {
1261
+ id: world.summary.id,
1262
+ name: world.summary.name
1263
+ }
1264
+ }, { vectors: false });
1265
+ try {
1266
+ const session = scratch;
1267
+ populateLocations(session, parts.locations);
1268
+ populateCharacters(session, parts.characters, player?.id ?? "");
1269
+ populateItems(session, parts.items, parts.slots, parts.locations);
1270
+ populateKnowledge(session, parts.characters);
1271
+ populateVariables(session, parts.variables, {
1272
+ characters: parts.characters,
1273
+ items: parts.items,
1274
+ locations: parts.locations,
1275
+ values: world.variables
1276
+ });
1277
+ populateClock(session, DEFAULT_SETTINGS.clock, world.clock, wall);
1278
+ observeAsPlayer(session, 1);
1279
+ const view = playerViewOf(session, {
1280
+ zone: world.clock?.timeZone ?? "UTC",
1281
+ wall
1282
+ });
1283
+ const { revision: _, ...rest } = view;
1284
+ return {
1285
+ ...rest,
1286
+ api: 1,
1287
+ suggestions: SAMPLE_SUGGESTIONS,
1288
+ revision: `preview-${view.revision}`
1289
+ };
1290
+ } finally {
1291
+ scratch.close();
1292
+ }
1293
+ }
1294
+ //#endregion
1295
+ //#region src/host/interface/storage.ts
1296
+ const keyOf$1 = (pack) => `roleplay.interface.${pack}`;
1297
+ function checkedKey(key) {
1298
+ if (key === "" || key.length > 100) throw new RangeError("a key is 1 to 100 characters");
1299
+ return key;
1300
+ }
1301
+ function read(session, pack) {
1302
+ const stored = session.metadata.getValue(keyOf$1(pack));
1303
+ return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? stored : {};
1304
+ }
1305
+ /** What a pack keeps in a session: small JSON values by name. */
1306
+ var PackStorage = class {
1307
+ session;
1308
+ pack;
1309
+ constructor(session, pack) {
1310
+ this.session = session;
1311
+ this.pack = pack;
1312
+ }
1313
+ get(key) {
1314
+ return read(this.session, this.pack)[checkedKey(key)] ?? null;
1315
+ }
1316
+ /** @throws {RangeError} when the store would pass its limit. */
1317
+ set(key, value) {
1318
+ const next = {
1319
+ ...read(this.session, this.pack),
1320
+ [checkedKey(key)]: value === void 0 ? null : value
1321
+ };
1322
+ let json;
1323
+ try {
1324
+ json = JSON.stringify(next);
1325
+ } catch {
1326
+ throw new RangeError("a stored value must be JSON");
1327
+ }
1328
+ if (Buffer.byteLength(json) > PACK_LIMITS.storageBytes) throw new RangeError(`a pack keeps at most ${PACK_LIMITS.storageBytes / 1024} KB in a story`);
1329
+ this.session.metadata.setValue(keyOf$1(this.pack), next);
1330
+ }
1331
+ remove(key) {
1332
+ checkedKey(key);
1333
+ const { [key]: _removed, ...rest } = read(this.session, this.pack);
1334
+ this.session.metadata.setValue(keyOf$1(this.pack), rest);
1335
+ }
1336
+ };
1337
+ //#endregion
1338
+ //#region src/host/interface/service.ts
1339
+ /** The packs of a world cannot be brought into a story because some of them have problems. */
1340
+ var InvalidPacksError = class extends Error {
1341
+ problems;
1342
+ constructor(message, problems) {
1343
+ super(message);
1344
+ this.problems = problems;
1345
+ }
1346
+ };
1347
+ /** What stands for a pack looked at in the editor where a session id would be; the key after it is the frame's. */
1348
+ const PREVIEW = "preview:";
1349
+ const addressFor = (session) => (path) => `roleplay-api/sessions/interface/pack/${session}/${path.split("/").map(encodeURIComponent).join("/")}`;
1350
+ /** What the interface packs of the stories show and do, for the browser. */
1351
+ var InterfaceService = class {
1352
+ deps;
1353
+ keys = /* @__PURE__ */ new Map();
1354
+ keyOf = /* @__PURE__ */ new Map();
1355
+ /** The pack folders being previewed, by frame key. */
1356
+ previews = /* @__PURE__ */ new Map();
1357
+ constructor(deps) {
1358
+ this.deps = deps;
1359
+ }
1360
+ /** The key of a session's frames: the same for as long as the host runs, unguessable. */
1361
+ frameKey(session) {
1362
+ const known = this.keyOf.get(session);
1363
+ if (known !== void 0) return known;
1364
+ const key = randomBytes(24).toString("base64url");
1365
+ this.keyOf.set(session, key);
1366
+ this.keys.set(key, session);
1367
+ return key;
1368
+ }
1369
+ /** The session a frame key belongs to, if it is one the host made. */
1370
+ sessionOfFrame(key) {
1371
+ return this.keys.get(key);
1372
+ }
1373
+ sessions() {
1374
+ return join(this.deps.root(), "sessions");
1375
+ }
1376
+ async worldOf(worldId) {
1377
+ const world = await this.deps.world(worldId);
1378
+ if (world === void 0) throw new WorldNotFoundError(`there is no world "${worldId}"`);
1379
+ return world;
1380
+ }
1381
+ /** The packs of a world, each with what it holds and what is wrong with it. @throws {WorldNotFoundError} */
1382
+ async worldPacks(worldId) {
1383
+ const { directory } = await this.worldOf(worldId);
1384
+ return packIds(directory).map((id) => {
1385
+ const { pack, problems } = readPack(join(directory, "ui", id), id, (file) => file);
1386
+ if (pack === void 0) return {
1387
+ id,
1388
+ name: id,
1389
+ version: "",
1390
+ description: "",
1391
+ actions: [],
1392
+ surfaces: {},
1393
+ tokens: 0,
1394
+ files: [],
1395
+ problems
1396
+ };
1397
+ const { manifest } = pack;
1398
+ return {
1399
+ id,
1400
+ name: manifest.name,
1401
+ version: manifest.version,
1402
+ description: manifest.description,
1403
+ actions: manifest.actions,
1404
+ surfaces: manifest.surfaces,
1405
+ ...manifest.skin === void 0 ? {} : { skin: manifest.skin },
1406
+ tokens: Object.keys(manifest.theme).length,
1407
+ files: [...pack.files].map(([path, file]) => ({
1408
+ path,
1409
+ size: file.size
1410
+ })),
1411
+ problems
1412
+ };
1413
+ });
1414
+ }
1415
+ /**
1416
+ * 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.
1417
+ * @throws {WorldNotFoundError} when the world, or the pack in it, is not there.
1418
+ * @throws {InvalidPacksError} when the pack has problems.
1419
+ * @throws {InvalidEditProblems} when the rest of the world has problems of its own.
1420
+ */
1421
+ async preview(worldId, packId) {
1422
+ const world = await this.worldOf(worldId);
1423
+ const folder = join(world.directory, "ui", packId);
1424
+ if (!isPackId(packId) || !existsSync(folder)) throw new WorldNotFoundError(`the world carries no pack "${packId}"`);
1425
+ const name = `${worldId}\n${packId}`;
1426
+ const key = this.keyOf.get(`${PREVIEW}${name}`) ?? randomBytes(24).toString("base64url");
1427
+ const { pack, problems } = readPack(folder, packId, addressFor(`${PREVIEW}${key}`));
1428
+ if (pack === void 0) throw new InvalidPacksError(`the pack "${packId}" has ${problems.length} problem(s)`, problems.map((problem) => ({
1429
+ path: problem.file,
1430
+ message: problem.message
1431
+ })));
1432
+ this.keyOf.set(`${PREVIEW}${name}`, key);
1433
+ this.keys.set(key, `${PREVIEW}${key}`);
1434
+ this.previews.set(key, {
1435
+ folder,
1436
+ pack: packId
1437
+ });
1438
+ return {
1439
+ pack: describePack(pack, key),
1440
+ view: await previewViewOf(world, (this.deps.wall ?? Date.now)())
1441
+ };
1442
+ }
1443
+ session(id) {
1444
+ if (!isSessionId(id) || !existsSync(sessionDatabase(this.sessions(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1445
+ return {
1446
+ folder: sessionFolder(this.sessions(), id),
1447
+ session: this.deps.open(id)
1448
+ };
1449
+ }
1450
+ /** The pack the session uses, read afresh. */
1451
+ active(id) {
1452
+ const { folder } = this.session(id);
1453
+ return activePack(folder, this.deps.root(), liveSettings(folder).interface.pack, () => addressFor(id));
1454
+ }
1455
+ describe(id) {
1456
+ const active = this.active(id);
1457
+ return {
1458
+ pack: active.pack === void 0 ? null : describePack(active.pack, this.frameKey(id)),
1459
+ problems: active.problems
1460
+ };
1461
+ }
1462
+ /** The player view, or that it is the one the caller has (`revision`). */
1463
+ view(id, revision) {
1464
+ const { folder, session } = this.session(id);
1465
+ const settings = liveSettings(folder);
1466
+ const view = playerViewOf(session, {
1467
+ zone: zoneOf(settings.clock),
1468
+ wall: (this.deps.wall ?? Date.now)()
1469
+ });
1470
+ return revision !== void 0 && revision === view.revision ? { unchanged: true } : { view };
1471
+ }
1472
+ /** What the settings of a story show: the pack in use, the packs it could use, and how the world's packs compare with its copies. */
1473
+ async status(id) {
1474
+ const { folder, session } = this.session(id);
1475
+ const root = this.deps.root();
1476
+ const active = this.active(id);
1477
+ const choice = (base, from) => (name) => {
1478
+ const { pack, problems } = readPack(join(base, "ui", name), name, (file) => file);
1479
+ return {
1480
+ id: name,
1481
+ name: pack?.manifest.name ?? name,
1482
+ from,
1483
+ surfaces: pack === void 0 ? [] : Object.keys(pack.manifest.surfaces),
1484
+ problems
1485
+ };
1486
+ };
1487
+ const own = packIds(folder);
1488
+ const available = [...own.map(choice(folder, "story")), ...packIds(root).filter((name) => !own.includes(name)).map(choice(root, "root"))];
1489
+ const reference = session.metadata.get().world;
1490
+ const worldDirectory = reference === void 0 ? void 0 : await this.deps.worldDirectory(reference.id);
1491
+ return {
1492
+ setting: liveSettings(folder).interface.pack,
1493
+ ...active.pack === void 0 ? {} : { active: active.pack.id },
1494
+ problems: active.problems,
1495
+ available,
1496
+ ...worldDirectory === void 0 || reference === void 0 ? {} : { world: {
1497
+ name: reference.name,
1498
+ packs: worldPackStates(worldDirectory, folder).map(({ id: name, state }) => {
1499
+ const { pack, problems } = readPack(join(worldDirectory, "ui", name), name, (file) => file);
1500
+ return {
1501
+ id: name,
1502
+ name: pack?.manifest.name ?? name,
1503
+ state,
1504
+ problems
1505
+ };
1506
+ })
1507
+ } }
1508
+ };
1509
+ }
1510
+ /**
1511
+ * Brings the world's packs into the story, replacing a copy that differs (the old one goes to the story's `.trash`).
1512
+ * @throws {WorldNotFoundError} when the person no longer has the world.
1513
+ * @throws {InvalidPacksError} when a pack of the world has problems; nothing is changed then.
1514
+ */
1515
+ async sync(id) {
1516
+ const { folder, session } = this.session(id);
1517
+ const reference = session.metadata.get().world;
1518
+ const worldDirectory = reference === void 0 ? void 0 : await this.deps.worldDirectory(reference.id);
1519
+ if (worldDirectory === void 0) throw new WorldNotFoundError("the world this story was started from is not among your worlds any more");
1520
+ const { problems, ...result } = syncWorldPacks(worldDirectory, folder);
1521
+ if (problems.length > 0) throw new InvalidPacksError(`the interface packs of the world have ${problems.length} problem(s); nothing was changed`, problems);
1522
+ return result;
1523
+ }
1524
+ /** The latest turns the player has been through, oldest first, as the story stands now: numbered as played (the number `story.turn` counts), without a turn taken back or one not yet told. */
1525
+ history(id, limit = PACK_LIMITS.history.fallback) {
1526
+ const { folder } = this.session(id);
1527
+ const timeline = readTimeline(folder);
1528
+ return pathTo(timeline, timeline.head).filter((node) => node.output !== void 0).map((node, index) => ({
1529
+ turn: index + 1,
1530
+ player: node.player,
1531
+ segments: (node.output?.segments ?? []).map((segment) => segment.type === "utterance" ? {
1532
+ type: "utterance",
1533
+ name: segment.name,
1534
+ text: segment.text
1535
+ } : {
1536
+ type: "narration",
1537
+ text: segment.text
1538
+ }),
1539
+ ...node.output?.ooc === void 0 ? {} : { note: node.output.ooc.note }
1540
+ })).slice(-Math.min(Math.max(1, limit), PACK_LIMITS.history.max));
1541
+ }
1542
+ /** A file of the session's pack; a page of it comes with the bridge. @returns nothing when the pack has no such file. */
1543
+ file(id, path) {
1544
+ const pack = id.startsWith(PREVIEW) ? this.previewed(id) : this.active(id).pack;
1545
+ const found = pack === void 0 ? void 0 : packFile(pack, path);
1546
+ if (found === void 0) return void 0;
1547
+ return found.mediaType.startsWith("text/html") ? {
1548
+ kind: "page",
1549
+ body: withBridge(readFileSync(found.file, "utf8")),
1550
+ mediaType: found.mediaType
1551
+ } : {
1552
+ kind: "file",
1553
+ ...found
1554
+ };
1555
+ }
1556
+ /** The pack of a preview, read afresh. */
1557
+ previewed(id) {
1558
+ const shown = this.previews.get(id.slice(8));
1559
+ return shown === void 0 ? void 0 : readPack(shown.folder, shown.pack, addressFor(id)).pack;
1560
+ }
1561
+ /** What the pack keeps in the session. @throws {RangeError} when a value does not fit. */
1562
+ storage(id, request) {
1563
+ const { session } = this.session(id);
1564
+ const { pack } = this.active(id);
1565
+ if (pack === void 0) throw new RangeError("the story uses no pack");
1566
+ const store = new PackStorage(session, pack.id);
1567
+ if (request.op === "get") return store.get(request.key);
1568
+ if (request.op === "set") store.set(request.key, request.value);
1569
+ else store.remove(request.key);
1570
+ return null;
1571
+ }
1572
+ /** Whether any pack with a tab exists in the root, a world or a story. */
1573
+ availability() {
1574
+ const root = this.deps.root();
1575
+ const inside = (folder) => existsSync(folder) ? readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join(folder, entry.name)) : [];
1576
+ return { tab: anyTab([
1577
+ root,
1578
+ ...inside(join(root, "worlds")),
1579
+ ...inside(join(root, "sessions"))
1580
+ ]) };
1581
+ }
1582
+ };
1583
+ //#endregion
1584
+ //#region src/host/interface/routes.ts
1585
+ /** The address under which the files of a session's pack are served to the page: `<prefix>/<session id>/<path of the file>`. */
1586
+ const PACK_FILES = "/sessions/interface/pack/";
1587
+ /**
1588
+ * The address under which a surface loads its own files: `<prefix>/<key>/<path of the file>`. A sandboxed frame has no
1589
+ * origin and so no cookie, so these are served without a login; the key is long, random and belongs to one story.
1590
+ */
1591
+ const FRAME_FILES = "/sessions/interface/frame/";
1592
+ const notFound = (res, error) => {
1593
+ if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1594
+ throw error;
1595
+ };
1596
+ function storageRequest(body) {
1597
+ if (typeof body !== "object" || body === null) return "the request must be an object";
1598
+ const { op, key, value } = body;
1599
+ if (op !== "get" && op !== "set" && op !== "remove") return "op must be get, set or remove";
1600
+ if (typeof key !== "string" || key === "") return "key must be text";
1601
+ return {
1602
+ op,
1603
+ key,
1604
+ ...value === void 0 ? {} : { value }
1605
+ };
1606
+ }
1607
+ function interfaceRoutes(api) {
1608
+ return {
1609
+ "/sessions/interface": { GET: async (_req, res, url) => {
1610
+ try {
1611
+ sendJson(res, 200, api.describe(url.searchParams.get("id") ?? ""));
1612
+ } catch (error) {
1613
+ notFound(res, error);
1614
+ }
1615
+ } },
1616
+ "/sessions/interface/view": { GET: async (_req, res, url) => {
1617
+ try {
1618
+ sendJson(res, 200, api.view(url.searchParams.get("id") ?? "", url.searchParams.get("revision") ?? void 0));
1619
+ } catch (error) {
1620
+ notFound(res, error);
1621
+ }
1622
+ } },
1623
+ "/sessions/interface/history": { GET: async (_req, res, url) => {
1624
+ const asked = Number(url.searchParams.get("limit"));
1625
+ try {
1626
+ sendJson(res, 200, api.history(url.searchParams.get("id") ?? "", Number.isInteger(asked) && asked > 0 ? asked : void 0));
1627
+ } catch (error) {
1628
+ notFound(res, error);
1629
+ }
1630
+ } },
1631
+ "/sessions/interface/storage": { POST: async (req, res, url) => {
1632
+ const request = storageRequest(await readJsonBody(req));
1633
+ if (typeof request === "string") return sendError(res, 400, request);
1634
+ try {
1635
+ sendJson(res, 200, { value: api.storage(url.searchParams.get("id") ?? "", request) });
1636
+ } catch (error) {
1637
+ if (error instanceof RangeError) return sendError(res, 422, error.message);
1638
+ notFound(res, error);
1639
+ }
1640
+ } },
1641
+ "/sessions/interface/status": { GET: async (_req, res, url) => {
1642
+ try {
1643
+ sendJson(res, 200, await api.status(url.searchParams.get("id") ?? ""));
1644
+ } catch (error) {
1645
+ notFound(res, error);
1646
+ }
1647
+ } },
1648
+ "/sessions/interface/sync": { POST: async (_req, res, url) => {
1649
+ try {
1650
+ sendJson(res, 200, await api.sync(url.searchParams.get("id") ?? ""));
1651
+ } catch (error) {
1652
+ if (error instanceof InvalidPacksError) return sendJson(res, 422, {
1653
+ message: error.message,
1654
+ problems: error.problems
1655
+ });
1656
+ notFound(res, error);
1657
+ }
1658
+ } },
1659
+ "/worlds/interface": { GET: async (_req, res, url) => {
1660
+ try {
1661
+ sendJson(res, 200, await api.worldPacks(url.searchParams.get("id") ?? ""));
1662
+ } catch (error) {
1663
+ notFound(res, error);
1664
+ }
1665
+ } },
1666
+ "/worlds/interface/preview": { GET: async (_req, res, url) => {
1667
+ try {
1668
+ sendJson(res, 200, await api.preview(url.searchParams.get("id") ?? "", url.searchParams.get("pack") ?? ""));
1669
+ } catch (error) {
1670
+ if (error instanceof InvalidPacksError) return sendJson(res, 422, {
1671
+ message: error.message,
1672
+ problems: error.problems.map((problem) => `${problem.path === "" ? "" : `${problem.path}: `}${problem.message}`)
1673
+ });
1674
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
1675
+ message: error.message,
1676
+ problems: error.problems
1677
+ });
1678
+ notFound(res, error);
1679
+ }
1680
+ } },
1681
+ "/interface/availability": { GET: async (_req, res) => {
1682
+ sendJson(res, 200, api.availability());
1683
+ } }
1684
+ };
1685
+ }
1686
+ /** Serves one file of a session's pack, for a path like `/sessions/interface/pack/<id>/<file>` or `/sessions/interface/frame/<key>/<file>`. */
1687
+ async function sendPackFile(api, path, res) {
1688
+ const framed = path.startsWith(FRAME_FILES);
1689
+ const rest = path.slice((framed ? FRAME_FILES : PACK_FILES).length);
1690
+ const slash = rest.indexOf("/");
1691
+ if (slash <= 0) return sendError(res, 404, "not found");
1692
+ const session = framed ? api.sessionOfFrame(rest.slice(0, slash)) : rest.slice(0, slash);
1693
+ if (session === void 0) return sendError(res, 404, "not found");
1694
+ let file;
1695
+ try {
1696
+ file = api.file(session, rest.slice(slash + 1).split("/").map(decodeURIComponent).join("/"));
1697
+ } catch (error) {
1698
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
1699
+ if (error instanceof URIError) return sendError(res, 400, "the path is not valid");
1700
+ throw error;
1701
+ }
1702
+ if (file === void 0) return sendError(res, 404, "the pack has no such file");
1703
+ res.statusCode = 200;
1704
+ for (const [name, value] of Object.entries(PACK_HEADERS)) res.setHeader(name, value);
1705
+ res.setHeader("content-type", file.mediaType);
1706
+ if (framed) res.setHeader("access-control-allow-origin", "*");
1707
+ if (file.kind === "page") {
1708
+ const body = Buffer.from(file.body);
1709
+ res.setHeader("content-length", body.length);
1710
+ res.end(body);
1711
+ return;
1712
+ }
1713
+ res.setHeader("content-length", file.size);
1714
+ await pipeline(createReadStream(file.file), res);
1715
+ }
985
1716
  //#endregion
986
1717
  //#region src/host/http/api.ts
987
1718
  /** The largest picture that can be added to a gallery. */
@@ -1033,7 +1764,7 @@ function languageField(value) {
1033
1764
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
1034
1765
  }
1035
1766
  }
1036
- function createApiHandler({ worlds, createWorld, starter, authorWorld, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, connection, speech }) {
1767
+ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech }) {
1037
1768
  const routes = {
1038
1769
  "/speech/capabilities": { GET: async (_req, res) => {
1039
1770
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1823,6 +2554,28 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
1823
2554
  return sendError(res, 404, error instanceof Error ? error.message : String(error));
1824
2555
  }
1825
2556
  } },
2557
+ "/sessions/activity/run": { GET: async (_req, res, url) => {
2558
+ try {
2559
+ const detail = sessions.activityRun(url.searchParams.get("id") ?? "", url.searchParams.get("run") ?? "");
2560
+ if (detail === void 0) return sendError(res, 404, "this run was not kept, or has been dropped to make room");
2561
+ sendJson(res, 200, detail);
2562
+ } catch (error) {
2563
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2564
+ if (error instanceof RangeError) return sendError(res, 400, error.message);
2565
+ throw error;
2566
+ }
2567
+ } },
2568
+ "/sessions/reflect": { POST: async (_req, res, url) => {
2569
+ try {
2570
+ await sessions.reflect(url.searchParams.get("id") ?? "");
2571
+ } catch (error) {
2572
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2573
+ if (error instanceof ReflectionRefusedError) return sendError(res, 409, error.message);
2574
+ throw error;
2575
+ }
2576
+ res.statusCode = 202;
2577
+ res.end();
2578
+ } },
1826
2579
  "/sessions/vectors/reset": { POST: async (_req, res, url) => {
1827
2580
  try {
1828
2581
  sessions.resetVectors(url.searchParams.get("id") ?? "");
@@ -1859,6 +2612,7 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
1859
2612
  res.statusCode = 204;
1860
2613
  res.end();
1861
2614
  } },
2615
+ ...interfaceRoutes(packs),
1862
2616
  "/worlds/cover": { GET: async (_req, res, url) => {
1863
2617
  const cover = await worlds.cover(url.searchParams.get("id") ?? "");
1864
2618
  if (cover === void 0) return sendError(res, 404, "no cover");
@@ -1871,14 +2625,24 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
1871
2625
  } }
1872
2626
  };
1873
2627
  return async (req, res) => {
1874
- const rejection = connection.requestRejection(req);
2628
+ const url = new URL(req.url ?? "/", "http://localhost");
2629
+ const path = url.pathname.slice(`/roleplay-api`.length) || "/";
2630
+ const framed = path.startsWith("/sessions/interface/frame/") && req.method === "GET";
2631
+ const rejection = framed ? void 0 : connection.requestRejection(req);
1875
2632
  if (rejection !== void 0) {
1876
2633
  res.statusCode = rejection;
1877
2634
  res.end();
1878
2635
  return;
1879
2636
  }
1880
- const url = new URL(req.url ?? "/", "http://localhost");
1881
- const path = url.pathname.slice(`/roleplay-api`.length) || "/";
2637
+ if ((path.startsWith("/sessions/interface/pack/") || framed) && req.method === "GET") {
2638
+ try {
2639
+ await sendPackFile(packs, path, res);
2640
+ } catch (error) {
2641
+ if (res.headersSent) res.destroy();
2642
+ else sendError(res, 500, error instanceof Error ? error.message : "internal error");
2643
+ }
2644
+ return;
2645
+ }
1882
2646
  const methods = routes[path];
1883
2647
  if (methods === void 0) return sendError(res, 404, "not found");
1884
2648
  const route = methods[req.method ?? ""];
@@ -2466,6 +3230,22 @@ function worldOf(session, sessionsDir) {
2466
3230
  definition: plot,
2467
3231
  progress
2468
3232
  }));
3233
+ const triggers = session.triggers.list().map((trigger) => ({
3234
+ key: trigger.key,
3235
+ name: trigger.name,
3236
+ when: trigger.condition,
3237
+ effects: trigger.effects,
3238
+ repeat: trigger.repeat,
3239
+ priority: trigger.priority,
3240
+ ...trigger.cooldownSeconds === void 0 ? {} : { cooldownSeconds: trigger.cooldownSeconds },
3241
+ ...trigger.chance === void 0 ? {} : { chance: trigger.chance },
3242
+ ...trigger.expires === void 0 ? {} : { expires: trigger.expires },
3243
+ announced: trigger.announce !== void 0,
3244
+ status: trigger.status,
3245
+ fireCount: trigger.fireCount,
3246
+ origin: trigger.origin,
3247
+ problems: trigger.problem === void 0 ? [] : [trigger.problem]
3248
+ }));
2469
3249
  return {
2470
3250
  ...typeof narrationVoice === "string" ? { narrationVoice } : {},
2471
3251
  characters,
@@ -2473,6 +3253,7 @@ function worldOf(session, sessionsDir) {
2473
3253
  things,
2474
3254
  factions,
2475
3255
  lore,
3256
+ triggers,
2476
3257
  plots,
2477
3258
  relations
2478
3259
  };
@@ -3150,6 +3931,8 @@ async function startSession(deps, request) {
3150
3931
  if (avatars !== void 0) for (const entry of brought) await copyPortrait(avatars, entry.from, entry.document, sessionFolder(sessionsDir, id), entry.id);
3151
3932
  const promptProblems = copyWorldPrompts(world.directory, sessionFolder(sessionsDir, id));
3152
3933
  if (promptProblems.length > 0) throw new InvalidWorldError(`the prompts of "${world.summary.name}" have ${promptProblems.length} problem(s)`, promptProblems);
3934
+ const packProblems = copyWorldPacks(world.directory, sessionFolder(sessionsDir, id));
3935
+ if (packProblems.length > 0) throw new InvalidWorldError(`the interface packs of "${world.summary.name}" have ${packProblems.length} problem(s)`, packProblems);
3153
3936
  writeSettings(sessionFolder(sessionsDir, id), settings);
3154
3937
  addToNote(session, "world", 1, worldFindings(session));
3155
3938
  chatSessionId = await deps.agent.ensure(id, name, opening);
@@ -3295,11 +4078,41 @@ function payloadOf(deps, id, settings) {
3295
4078
  pendingRecords: deps.pendingRecords(id),
3296
4079
  pendingConsolidation: deps.pendingConsolidation(id),
3297
4080
  activity: deps.activity(id),
4081
+ interventions: deps.interventions(id),
3298
4082
  vectors: deps.vectors(id),
4083
+ reflection: deps.reflection(id),
3299
4084
  ...clockMode === void 0 ? {} : { clockMode }
3300
4085
  };
3301
4086
  }
3302
4087
  //#endregion
4088
+ //#region src/host/interface/first-party.ts
4089
+ /** The folder of the packs shipped with the package. */
4090
+ const FIRST_PARTY_FOLDER = "packs";
4091
+ /** Found from this module, so that it works from source and from the build. */
4092
+ function firstPartyDirectory(from = dirname(fileURLToPath(import.meta.url))) {
4093
+ for (let directory = from;; directory = dirname(directory)) {
4094
+ const candidate = join(directory, FIRST_PARTY_FOLDER);
4095
+ if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
4096
+ if (dirname(directory) === directory) throw new Error("the interface packs shipped with the package were not found");
4097
+ }
4098
+ }
4099
+ /**
4100
+ * 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
4101
+ * that is there is never overwritten, so it can be edited; one that was deleted comes back.
4102
+ * @returns the packs that were put there.
4103
+ */
4104
+ function installFirstPartyPacks(root, shipped = firstPartyDirectory()) {
4105
+ const installed = [];
4106
+ for (const entry of readdirSync(shipped, { withFileTypes: true })) {
4107
+ if (!entry.isDirectory() || !isPackId(entry.name)) continue;
4108
+ const target = join(root, "ui", entry.name);
4109
+ if (existsSync(target)) continue;
4110
+ cpSync(join(shipped, entry.name), target, { recursive: true });
4111
+ installed.push(entry.name);
4112
+ }
4113
+ return installed;
4114
+ }
4115
+ //#endregion
3303
4116
  //#region src/host/sessions/vectors.ts
3304
4117
  /** How many waiting texts are counted before saying "that many": the number is for reassurance, not accounting. */
3305
4118
  const MAX_COUNTED = 1e4;
@@ -3323,6 +4136,24 @@ function resetVectors(session) {
3323
4136
  session.recallIndex.reset();
3324
4137
  }
3325
4138
  //#endregion
4139
+ //#region src/host/sessions/interventions.ts
4140
+ /** What the story's triggers delivered lately and what became of each, oldest first. */
4141
+ function readInterventions(session) {
4142
+ const withdrawn = readWithdrawn(session);
4143
+ return session.triggers.notes().slice(-30).map((note) => {
4144
+ const reason = note.status === "lapsed" ? withdrawn[note.id] : void 0;
4145
+ return {
4146
+ turn: note.turn,
4147
+ kind: note.kind,
4148
+ text: note.text,
4149
+ trigger: session.triggers.get(note.triggerId)?.key ?? "",
4150
+ characters: note.characterIds.flatMap((id) => session.characters.get(id)?.name ?? []),
4151
+ status: note.status === "pending" ? "waiting" : note.status === "done" ? "taken" : reason === void 0 ? "lapsed" : "withdrawn",
4152
+ ...reason === void 0 ? {} : { reason }
4153
+ };
4154
+ });
4155
+ }
4156
+ //#endregion
3326
4157
  //#region src/host/sessions/open-session.ts
3327
4158
  /** Make sure a session has its DSH chat, so that it can be opened. */
3328
4159
  async function openSession(deps, id) {
@@ -3815,6 +4646,7 @@ function apply(ctx, config) {
3815
4646
  const worlds = new WorldCatalog(ctx, root);
3816
4647
  const prompts = new PromptLibrary(ctx, root);
3817
4648
  prompts.bootstrap();
4649
+ installFirstPartyPacks(root.path);
3818
4650
  const languages = new AuthoringLanguages(ctx, () => join(root.path, "worlds"));
3819
4651
  const agent = new AgentSessions(agentServicesOf(ctx), () => root.path);
3820
4652
  const authoring = new AuthoringSessions(agentServicesOf(ctx), () => root.path, prompts, languages);
@@ -3832,7 +4664,9 @@ function apply(ctx, config) {
3832
4664
  clockMode: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).clock.get()?.mode,
3833
4665
  pendingConsolidation: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).consolidation.pending().length,
3834
4666
  vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
3835
- activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
4667
+ reflection: (id) => reflectionStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id), ctx.roleplayOrchestration.reflecting(chatSessionId(id))),
4668
+ activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4669
+ interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
3836
4670
  };
3837
4671
  const purgeChat = purgeOf(ctx, config.sessionStorePath);
3838
4672
  const deps = {
@@ -3843,6 +4677,12 @@ function apply(ctx, config) {
3843
4677
  avatars: () => avatarsWorld(root.path)
3844
4678
  };
3845
4679
  registerApi(ctx, {
4680
+ packs: new InterfaceService({
4681
+ open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
4682
+ root: () => root.path,
4683
+ worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory,
4684
+ world: (worldId) => worlds.find(worldId)
4685
+ }),
3846
4686
  speech: {
3847
4687
  voices: async () => await voicesOf(textToSpeechOf(ctx)),
3848
4688
  speak: async (parts) => await speakParts(textToSpeechOf(ctx), parts),
@@ -4010,6 +4850,16 @@ function apply(ctx, config) {
4010
4850
  writeSettings: (id, value) => writeChatSettings(settingsDeps, id, value),
4011
4851
  timeline: (id) => timelinesOf(ctx, deps.sessionsDir, id).view(id),
4012
4852
  moveTimeline: (id, to) => timelinesOf(ctx, deps.sessionsDir, id).move(chatSessionId(id), to === "start" ? null : to),
4853
+ activityRun: (id, run) => {
4854
+ const sessions = join(root.path, "sessions");
4855
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
4856
+ return readRunDetail(sessionFolder(sessions, id), run);
4857
+ },
4858
+ reflect: async (id) => {
4859
+ const sessions = join(root.path, "sessions");
4860
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
4861
+ await ctx.roleplayOrchestration.reflect(chatSessionId(id));
4862
+ },
4013
4863
  resetVectors: (id) => {
4014
4864
  const sessions = join(root.path, "sessions");
4015
4865
  if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);