@dsh-agentic-roleplay/core 0.1.0 → 0.2.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 (80) hide show
  1. package/README.md +1 -1
  2. package/lib/{notes-CJzbN_-E.js → activity-t7OBgHlc.js} +267 -47
  3. package/lib/authoring.js +295 -14
  4. package/lib/client.js +2599 -648
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/{documents-BBq88wXP.js → documents-Bu5uYRZB.js} +54 -33
  8. package/lib/{gallery-CjG9_4Sz.js → gallery-DUeBMHQX.js} +2 -2
  9. package/lib/{generator-pxZS-pu-.js → generator-HPifO3Kk.js} +211 -15
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +849 -20
  12. package/lib/{narration-tYy6Rkfr.js → narration-BRyHU0H2.js} +28 -5
  13. package/lib/orchestration.js +803 -233
  14. package/lib/packs-ByP1J-zj.js +1334 -0
  15. package/lib/{presenter-agent-DbZALurg.js → presenter-agent-G43ODV8I.js} +3 -3
  16. package/package.json +5 -3
  17. package/prompts/en/roleplay/ask-answerer.md +3 -0
  18. package/prompts/en/roleplay/ask-question.md +2 -0
  19. package/prompts/en/roleplay/character-decide.md +1 -1
  20. package/prompts/en/roleplay/character-lookup.md +1 -1
  21. package/prompts/en/roleplay/faction-strategist.md +5 -0
  22. package/prompts/en/roleplay/game-master.md +5 -1
  23. package/prompts/en/roleplay/ooc-empty.md +1 -1
  24. package/prompts/en/roleplay/trigger-judge.md +3 -0
  25. package/prompts/en/world/procedure.md +1 -1
  26. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  27. package/prompts/zh/roleplay/ask-question.md +2 -0
  28. package/prompts/zh/roleplay/character-decide.md +1 -1
  29. package/prompts/zh/roleplay/character-lookup.md +1 -1
  30. package/prompts/zh/roleplay/faction-strategist.md +5 -0
  31. package/prompts/zh/roleplay/game-master.md +5 -1
  32. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  33. package/prompts/zh/roleplay/trigger-judge.md +3 -0
  34. package/prompts/zh/world/procedure.md +1 -1
  35. package/starter-worlds/blackwater-observatory/characters/arthur-moore/character.json +65 -0
  36. package/starter-worlds/blackwater-observatory/characters/clara-whitlock/character.json +87 -0
  37. package/starter-worlds/blackwater-observatory/characters/eleanor-graves/character.json +80 -0
  38. package/starter-worlds/blackwater-observatory/characters/marcus-reed/character.json +73 -0
  39. package/starter-worlds/blackwater-observatory/items/anonymous-letter/item.json +9 -0
  40. package/starter-worlds/blackwater-observatory/items/brass-laboratory-key/item.json +10 -0
  41. package/starter-worlds/blackwater-observatory/items/claras-gossip-notebook/item.json +9 -0
  42. package/starter-worlds/blackwater-observatory/items/harlans-notebook/item.json +10 -0
  43. package/starter-worlds/blackwater-observatory/items/investigators-coat/item.json +10 -0
  44. package/starter-worlds/blackwater-observatory/items/investigators-notebook/item.json +9 -0
  45. package/starter-worlds/blackwater-observatory/items/locked-filing-cabinet/item.json +10 -0
  46. package/starter-worlds/blackwater-observatory/items/marcus-calibration-notes/item.json +9 -0
  47. package/starter-worlds/blackwater-observatory/items/mayors-administrative-seal/item.json +9 -0
  48. package/starter-worlds/blackwater-observatory/items/municipal-lockbox/item.json +10 -0
  49. package/starter-worlds/blackwater-observatory/items/pocket-revolver/item.json +10 -0
  50. package/starter-worlds/blackwater-observatory/items/room-7-cash-receipt/item.json +9 -0
  51. package/starter-worlds/blackwater-observatory/items/rusting-mine-cart/item.json +10 -0
  52. package/starter-worlds/blackwater-observatory/items/signal-recording-strip/item.json +9 -0
  53. package/starter-worlds/blackwater-observatory/items/silver-pocket-watch/item.json +9 -0
  54. package/starter-worlds/blackwater-observatory/items/survey-archive-cabinet/item.json +10 -0
  55. package/starter-worlds/blackwater-observatory/items/surveyors-map/item.json +10 -0
  56. package/starter-worlds/blackwater-observatory/items/unknown-visitors-note-fragment/item.json +10 -0
  57. package/starter-worlds/blackwater-observatory/locations/blackwater-ridge/location.json +5 -0
  58. package/starter-worlds/blackwater-observatory/locations/iron-stag-bar/location.json +30 -0
  59. package/starter-worlds/blackwater-observatory/locations/iron-stag-room-7/location.json +18 -0
  60. package/starter-worlds/blackwater-observatory/locations/north-forest-cabin/location.json +18 -0
  61. package/starter-worlds/blackwater-observatory/locations/observatory-directors-office/location.json +20 -0
  62. package/starter-worlds/blackwater-observatory/locations/observatory-telescope-chamber/location.json +25 -0
  63. package/starter-worlds/blackwater-observatory/locations/old-mine-entrance/location.json +27 -0
  64. package/starter-worlds/blackwater-observatory/locations/old-mine-main-tunnel/location.json +13 -0
  65. package/starter-worlds/blackwater-observatory/locations/town-hall-mayors-office/location.json +25 -0
  66. package/starter-worlds/blackwater-observatory/locations/town-hall-records-room/location.json +13 -0
  67. package/starter-worlds/blackwater-observatory/locations/town-square/location.json +30 -0
  68. package/starter-worlds/blackwater-observatory/triggers.json +20 -0
  69. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  70. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  71. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  72. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  73. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  74. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  75. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  76. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  77. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  78. package/starter-worlds/blackwater-observatory/variables.json +39 -0
  79. package/starter-worlds/blackwater-observatory/world.json +27 -0
  80. package/lib/worlds-Bj-EGS_i.js +0 -478
package/lib/index.js CHANGED
@@ -1,21 +1,22 @@
1
1
  import { n as roleplaySessionOf, t as chatSessionId } from "./chat-AKrVcWIC.js";
2
- import { $ as CHARACTER_FILE_NAME, A as populateClock, B as loadLocations, E as markReady, F as populateLore, H as CHARACTERS_DIR, I as populateRoutines, J as readWorldPrompt, K as deleteWorldPrompt, L as populateTriggers, M as populateItems, N as populateKnowledge, O as loadValidatedWorld, P as populateLocations, Q as variableProblems, R as populateVariables, U as loadCharacters, V as loadItems, W as subfolders, X as VARIABLES_FILE_NAME, Y as writeWorldPrompt, Z as parseVariablesFile, _ as replaceFile$1, at as WORLD_FILE_NAME, b as authoringChatSessionId, c as editWorldLore$1, ct as InvalidEditProblems, d as editWorldPlots$1, dt as parseLoreEdit, et as parseCharacterFile, f as editWorldRelation$1, ft as parsePlaceEdit, g as readWorldEditor, h as generateWorldCharacterPortrait, ht as IMPORT_COMMAND, i as readAuthoredEntityDocument, it as parseChoices, j as populateFactions, k as populateCharacters, l as editWorldNarrationVoice, lt as parseCharacterEdit, m as entityFolder, mt as parseThingEdit, n as createAuthoredEntity, nt as ImportNotFoundError, o as editWorldCharacter$1, ot as parseWorldFile, p as editWorldThing$1, pt as parseRelationEdit, q as listWorldPrompts, r as deleteAuthoredEntity, rt as ImportStore, s as editWorldFaction$1, st as parseWorldInfoEdit, tt as IMPORT_FOLDER, u as editWorldPlace$1, ut as parseFactionEdit, v as worldCharacterPortraitFile, z as routineProblems } from "./documents-BBq88wXP.js";
3
- 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-tYy6Rkfr.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";
4
5
  import { n as VARIABLE_SUBJECTS, r as VARIABLE_VISIBILITIES, t as VARIABLE_KINDS } from "./src-CWTNeL6Y.js";
5
- 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-Bj-EGS_i.js";
6
- import { C as slug, E as childSamplingOf, a as addToLibrary, f as referenceImagePath, l as inheritImages, p as sceneImagePath, t as generateReferenceImage, w as uniqueKey } from "./generator-pxZS-pu-.js";
7
- import { d as plotProgressOf, f as populatePlots, g as defaultBoundaries, m as TimelineError, o as PLOTS_METADATA_KEY, r as notesOfSession } from "./notes-CJzbN_-E.js";
8
- import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-CjG9_4Sz.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";
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 { 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";
15
15
  import { inflateSync } from "node:zlib";
16
+ import { fileURLToPath } from "node:url";
16
17
  import { Service } from "@deepseek-ai/cordis";
17
- import { chmod, copyFile, lstat, mkdir, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
18
- import { isSessionId, parseInstant, sessionDatabase, sessionFolder, systemTimeZone } from "@dsh-agentic-roleplay/state";
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
20
  import { pipeline } from "node:stream/promises";
20
21
  import { homedir } from "node:os";
21
22
  import z from "@deepseek-ai/schemastery";
@@ -860,6 +861,72 @@ function parseVariablesEdit(value) {
860
861
  return declarations;
861
862
  }
862
863
  //#endregion
864
+ //#region src/host/worlds/starter.ts
865
+ const STARTER_FOLDER = "starter-worlds";
866
+ /** Names a starter world that the package does not ship. */
867
+ var UnknownStarterError = class extends Error {};
868
+ /** The folder of the worlds that ship with the package, found from this module so that it works from source and from the build. */
869
+ function starterDirectory(from = dirname(fileURLToPath(import.meta.url))) {
870
+ for (let directory = from;; directory = dirname(directory)) {
871
+ const candidate = join(directory, STARTER_FOLDER);
872
+ if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
873
+ if (dirname(directory) === directory) throw new Error("the starter worlds shipped with the package were not found");
874
+ }
875
+ }
876
+ async function shipped(directory) {
877
+ const found = [];
878
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
879
+ if (!entry.isDirectory()) continue;
880
+ const document = JSON.parse(await readFile(join(directory, entry.name, WORLD_FILE_NAME), "utf8"));
881
+ if (typeof document.id !== "string" || typeof document.name !== "string") throw new Error(`the starter world "${entry.name}" has no id or name`);
882
+ found.push({
883
+ folder: entry.name,
884
+ id: document.id,
885
+ name: document.name,
886
+ description: typeof document.description === "string" ? document.description : "",
887
+ tags: Array.isArray(document.metadata?.tags) ? document.metadata.tags.filter((tag) => typeof tag === "string") : []
888
+ });
889
+ }
890
+ return found.sort((a, b) => a.folder.localeCompare(b.folder));
891
+ }
892
+ /** The worlds the package ships, each with whether the person's worlds have it already. */
893
+ async function listStarterWorlds(catalog, directory = starterDirectory()) {
894
+ const known = await catalog.list();
895
+ return (await shipped(directory)).map(({ id, ...world }) => ({
896
+ ...world,
897
+ installed: known.worlds.some((existing) => existing.id === id) || existsSync(join(catalog.directory, world.folder))
898
+ }));
899
+ }
900
+ /**
901
+ * Copies a shipped world into the person's worlds, as a world of their own to play and edit, and makes the catalogue see it. Nothing is overwritten.
902
+ * @throws {UnknownStarterError} when the package ships no such world.
903
+ * @throws {WorldFolderExistsError} when the person already has that folder or a world with the same id.
904
+ */
905
+ async function addStarterWorld(catalog, folder, directory = starterDirectory()) {
906
+ const world = (await shipped(directory)).find((candidate) => candidate.folder === folder);
907
+ if (world === void 0) throw new UnknownStarterError(`there is no starter world "${folder}"`);
908
+ if ((await catalog.list({ refresh: true })).worlds.some((existing) => existing.id === world.id)) throw new WorldFolderExistsError(`you already have "${world.name}"`);
909
+ const target = join(catalog.directory, world.folder);
910
+ if (existsSync(target)) throw new WorldFolderExistsError(`a world folder named "${world.folder}" already exists`);
911
+ await mkdir(catalog.directory, { recursive: true });
912
+ try {
913
+ await cp(join(directory, world.folder), target, {
914
+ recursive: true,
915
+ errorOnExist: true,
916
+ force: false
917
+ });
918
+ } catch (error) {
919
+ await rm(target, {
920
+ recursive: true,
921
+ force: true
922
+ });
923
+ throw error;
924
+ }
925
+ const added = (await catalog.list({ refresh: true })).worlds.find((candidate) => candidate.id === world.id);
926
+ if (added === void 0) throw new Error(`added "${world.name}" but it was not found when the catalogue refreshed`);
927
+ return added;
928
+ }
929
+ //#endregion
863
930
  //#region src/host/http/respond.ts
864
931
  function sendJson(res, status, payload) {
865
932
  res.statusCode = status;
@@ -915,6 +982,581 @@ async function readBinaryBody(req, limit) {
915
982
  if (size === 0) throw new HttpError(400, "the upload is empty");
916
983
  return Buffer.concat(chunks);
917
984
  }
985
+ /** The headers of every file of a pack. */
986
+ const PACK_HEADERS = {
987
+ "content-security-policy": [
988
+ "sandbox allow-scripts",
989
+ "default-src 'none'",
990
+ "script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'",
991
+ "worker-src 'self' blob:",
992
+ "style-src 'self' 'unsafe-inline'",
993
+ "img-src 'self' data: blob:",
994
+ "font-src 'self' data:",
995
+ "media-src 'self' data: blob:",
996
+ "connect-src 'self'",
997
+ "frame-src 'self'",
998
+ "form-action 'none'",
999
+ "base-uri 'self'"
1000
+ ].join("; "),
1001
+ "x-content-type-options": "nosniff",
1002
+ "cache-control": "no-cache",
1003
+ "referrer-policy": "no-referrer"
1004
+ };
1005
+ /**
1006
+ * The `rp` object a surface sees. It is plain ES5 so that it runs wherever the page does, and it only
1007
+ * posts messages: every decision is the page's. Requests time out after 20 seconds.
1008
+ */
1009
+ const BRIDGE_SCRIPT = `(function () {
1010
+ var API = 1;
1011
+ var pending = {};
1012
+ var counter = 0;
1013
+ var watchers = [];
1014
+ var listeners = { turn: [], suggestions: [], theme: [] };
1015
+ var latest;
1016
+ function post(message) { message.rp = API; parent.postMessage(message, '*'); }
1017
+ function request(method, params) {
1018
+ return new Promise(function (resolve, reject) {
1019
+ var id = ++counter;
1020
+ var timer = setTimeout(function () { delete pending[id]; reject(new Error('rp.' + method + ' did not get an answer')); }, 20000);
1021
+ pending[id] = { resolve: resolve, reject: reject, timer: timer };
1022
+ post({ type: 'request', id: id, method: method, params: params });
1023
+ });
1024
+ }
1025
+ function each(list, value) { list.slice().forEach(function (listener) { try { listener(value); } catch (error) { console.error(error); } }); }
1026
+ function applyTheme(data) {
1027
+ var root = document.documentElement;
1028
+ root.setAttribute('data-rp-scheme', data.scheme);
1029
+ root.style.colorScheme = data.scheme;
1030
+ Object.keys(data.tokens).forEach(function (name) { root.style.setProperty(name, data.tokens[name]); });
1031
+ }
1032
+ function remove(list, listener) { var index = list.indexOf(listener); if (index >= 0) list.splice(index, 1); }
1033
+ window.addEventListener('message', function (event) {
1034
+ if (event.source !== parent) return;
1035
+ var message = event.data;
1036
+ if (!message || message.rp !== API) return;
1037
+ if (message.type === 'response') {
1038
+ var entry = pending[message.id];
1039
+ if (!entry) return;
1040
+ delete pending[message.id];
1041
+ clearTimeout(entry.timer);
1042
+ if (message.ok) entry.resolve(message.value); else entry.reject(new Error(message.error));
1043
+ } else if (message.type === 'event') {
1044
+ if (message.name === 'state') { latest = message.data; each(watchers, latest); }
1045
+ else if (message.name === 'theme') { applyTheme(message.data); each(listeners.theme, message.data); }
1046
+ else if (listeners[message.name]) each(listeners[message.name], message.data);
1047
+ }
1048
+ });
1049
+ function on(name, listener) {
1050
+ if (!listeners[name]) throw new Error('rp.on: there is no event "' + name + '"');
1051
+ listeners[name].push(listener);
1052
+ return function () { remove(listeners[name], listener); };
1053
+ }
1054
+ window.rp = Object.freeze({
1055
+ api: API,
1056
+ state: function () { return latest ? Promise.resolve(latest) : request('state'); },
1057
+ watch: function (listener) {
1058
+ watchers.push(listener);
1059
+ if (latest) listener(latest);
1060
+ return function () { remove(watchers, listener); };
1061
+ },
1062
+ on: on,
1063
+ say: function (text) { return request('say', { text: String(text) }); },
1064
+ fill: function (text) { return request('fill', { text: String(text) }); },
1065
+ choose: function (index) { return request('choose', { index: index }); },
1066
+ storage: {
1067
+ get: function (key) { return request('storage.get', { key: String(key) }); },
1068
+ set: function (key, value) { return request('storage.set', { key: String(key), value: value }); },
1069
+ remove: function (key) { return request('storage.remove', { key: String(key) }); }
1070
+ },
1071
+ history: function (limit) { return request('history', { limit: limit }); },
1072
+ open: function (surface) { return request('open', { surface: String(surface) }); },
1073
+ resize: function (height) { post({ type: 'resize', height: Number(height) }); },
1074
+ theme: function () { return request('theme'); }
1075
+ });
1076
+ post({ type: 'hello' });
1077
+ })();`;
1078
+ /**
1079
+ * A surface's HTML with the bridge put first, so that `rp` exists before any script of the pack runs.
1080
+ * It goes right after the opening of `<head>`, else of `<html>`, else at the top (never before a doctype).
1081
+ */
1082
+ function withBridge(html) {
1083
+ const script = `<script>${BRIDGE_SCRIPT}<\/script>`;
1084
+ for (const opening of [
1085
+ /<head(\s[^>]*)?>/i,
1086
+ /<html(\s[^>]*)?>/i,
1087
+ /<!doctype[^>]*>/i
1088
+ ]) {
1089
+ const match = opening.exec(html);
1090
+ if (match !== null) return `${html.slice(0, match.index + match[0].length)}${script}${html.slice(match.index + match[0].length)}`;
1091
+ }
1092
+ return `${script}${html}`;
1093
+ }
1094
+ //#endregion
1095
+ //#region src/host/interface/player-view.ts
1096
+ const keyOf$2 = (character) => character.sourceId ?? String(character.id);
1097
+ /** What a variable shows, in one line of data. */
1098
+ function shown(subject, entries) {
1099
+ return entries.map(({ variable, value }) => ({
1100
+ subject,
1101
+ name: variable.name,
1102
+ value: describeValue(variable, value)
1103
+ }));
1104
+ }
1105
+ /**
1106
+ * 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
1107
+ * player's character's side could see: nothing private, hidden or unknown is read, so nothing of it can leave through here.
1108
+ */
1109
+ function playerViewOf(session, options) {
1110
+ const metadata = session.metadata.get();
1111
+ const player = session.characters.list().find((character) => character.control === "player");
1112
+ const view = {
1113
+ api: 1,
1114
+ story: {
1115
+ name: metadata.name,
1116
+ turn: metadata.turns
1117
+ },
1118
+ map: {
1119
+ places: [],
1120
+ routes: []
1121
+ },
1122
+ carried: [],
1123
+ variables: [],
1124
+ suggestions: []
1125
+ };
1126
+ const clock = session.clock.get();
1127
+ if (clock !== void 0) {
1128
+ const now = clock.mode === "real" ? options.wall : clock.now;
1129
+ view.time = {
1130
+ iso: new Date(now).toISOString(),
1131
+ zone: options.zone,
1132
+ text: describeInstant(now, options.zone)
1133
+ };
1134
+ }
1135
+ view.variables.push(...shown("the world", shownVariables(session, "world", 0, "world", "others")));
1136
+ if (player === void 0) return finish(view, session);
1137
+ const playerState = session.characterStates.get(player.id);
1138
+ view.player = {
1139
+ key: keyOf$2(player),
1140
+ name: player.name,
1141
+ summary: player.summary,
1142
+ publicState: playerState?.publicState ?? ""
1143
+ };
1144
+ view.variables.push(...shown(player.name, shownVariables(session, "character", player.id, keyOf$2(player), "others")));
1145
+ const placement = session.placements.get("character", player.id);
1146
+ const here = placement === void 0 ? void 0 : session.locations.get(placement.locationId);
1147
+ const known = new Set(session.knowledge.list(player.id, "location").map((entry) => entry.subjectId));
1148
+ if (here !== void 0) {
1149
+ known.add(here.id);
1150
+ view.place = {
1151
+ key: locationKey(here),
1152
+ name: here.name,
1153
+ description: here.description,
1154
+ features: here.features.map((feature) => ({
1155
+ key: feature.key,
1156
+ name: feature.name
1157
+ })),
1158
+ exits: session.locations.exitsFrom(here.id).flatMap((exit) => {
1159
+ const to = known.has(exit.toId) ? session.locations.get(exit.toId) : void 0;
1160
+ return to === void 0 ? [] : [{
1161
+ name: to.name,
1162
+ open: exit.state === "open"
1163
+ }];
1164
+ }),
1165
+ items: session.items.contents({
1166
+ kind: "location",
1167
+ id: here.id
1168
+ }).filter((entry) => !entry.item.hidden).map((entry) => ({
1169
+ name: entry.item.name,
1170
+ quantity: entry.item.quantity
1171
+ })),
1172
+ here: session.placements.at(here.id, "character").flatMap((other) => {
1173
+ const character = other.entityId === player.id ? void 0 : session.characters.get(other.entityId);
1174
+ return character === void 0 ? [] : [{
1175
+ key: keyOf$2(character),
1176
+ name: character.name,
1177
+ publicState: session.characterStates.get(character.id)?.publicState ?? ""
1178
+ }];
1179
+ })
1180
+ };
1181
+ view.variables.push(...shown(here.name, shownVariables(session, "location", here.id, locationKey(here), "others")));
1182
+ for (const other of view.place.here) {
1183
+ const character = session.characters.list().find((candidate) => keyOf$2(candidate) === other.key);
1184
+ if (character !== void 0) view.variables.push(...shown(character.name, shownVariables(session, "character", character.id, other.key, "others")));
1185
+ }
1186
+ for (const entry of session.items.contents({
1187
+ kind: "location",
1188
+ id: here.id
1189
+ }).filter((candidate) => !candidate.item.hidden)) view.variables.push(...shown(entry.item.name, shownVariables(session, "item", entry.item.id, itemKey(entry.item), "others")));
1190
+ }
1191
+ view.carried = session.items.contents({
1192
+ kind: "character",
1193
+ id: player.id
1194
+ }).filter((entry) => !entry.item.hidden).map((entry) => {
1195
+ const holder = entry.holding.holder;
1196
+ return {
1197
+ name: entry.item.name,
1198
+ quantity: entry.item.quantity,
1199
+ where: holder.kind === "character" && holder.mode === "worn" ? `worn on the ${holder.slot}` : "carried"
1200
+ };
1201
+ });
1202
+ const places = [...known].flatMap((id) => {
1203
+ const place = session.locations.get(id);
1204
+ return place === void 0 ? [] : [place];
1205
+ });
1206
+ view.map.places = places.map((place) => ({
1207
+ key: locationKey(place),
1208
+ name: place.name,
1209
+ ...parentKey(session, place.parentId, known) === void 0 ? {} : { parent: parentKey(session, place.parentId, known) },
1210
+ here: place.id === here?.id
1211
+ }));
1212
+ const exits = session.locations.allExits();
1213
+ view.map.routes = session.knowledge.list(player.id, "exit").flatMap((entry) => {
1214
+ const exit = exits.find((candidate) => candidate.id === entry.subjectId);
1215
+ const from = exit === void 0 ? void 0 : session.locations.get(exit.fromId);
1216
+ const to = exit === void 0 ? void 0 : session.locations.get(exit.toId);
1217
+ return from === void 0 || to === void 0 || !known.has(from.id) || !known.has(to.id) ? [] : [{
1218
+ from: locationKey(from),
1219
+ to: locationKey(to)
1220
+ }];
1221
+ });
1222
+ return finish(view, session);
1223
+ }
1224
+ function parentKey(session, parentId, known) {
1225
+ const parent = parentId === void 0 || !known.has(parentId) ? void 0 : session.locations.get(parentId);
1226
+ return parent === void 0 ? void 0 : locationKey(parent);
1227
+ }
1228
+ function finish(view, session) {
1229
+ view.suggestions = readNotes(session).find((note) => note.kind === "suggestions")?.lines ?? [];
1230
+ const revision = createHash("sha256").update(JSON.stringify(view)).digest("hex").slice(0, 16);
1231
+ return {
1232
+ ...view,
1233
+ revision
1234
+ };
1235
+ }
1236
+ //#endregion
1237
+ //#region src/host/interface/storage.ts
1238
+ const keyOf$1 = (pack) => `roleplay.interface.${pack}`;
1239
+ function checkedKey(key) {
1240
+ if (key === "" || key.length > 100) throw new RangeError("a key is 1 to 100 characters");
1241
+ return key;
1242
+ }
1243
+ function read(session, pack) {
1244
+ const stored = session.metadata.getValue(keyOf$1(pack));
1245
+ return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? stored : {};
1246
+ }
1247
+ /** What a pack keeps in a session: small JSON values by name. */
1248
+ var PackStorage = class {
1249
+ session;
1250
+ pack;
1251
+ constructor(session, pack) {
1252
+ this.session = session;
1253
+ this.pack = pack;
1254
+ }
1255
+ get(key) {
1256
+ return read(this.session, this.pack)[checkedKey(key)] ?? null;
1257
+ }
1258
+ /** @throws {RangeError} when the store would pass its limit. */
1259
+ set(key, value) {
1260
+ const next = {
1261
+ ...read(this.session, this.pack),
1262
+ [checkedKey(key)]: value === void 0 ? null : value
1263
+ };
1264
+ let json;
1265
+ try {
1266
+ json = JSON.stringify(next);
1267
+ } catch {
1268
+ throw new RangeError("a stored value must be JSON");
1269
+ }
1270
+ if (Buffer.byteLength(json) > PACK_LIMITS.storageBytes) throw new RangeError(`a pack keeps at most ${PACK_LIMITS.storageBytes / 1024} KB in a story`);
1271
+ this.session.metadata.setValue(keyOf$1(this.pack), next);
1272
+ }
1273
+ remove(key) {
1274
+ checkedKey(key);
1275
+ const { [key]: _removed, ...rest } = read(this.session, this.pack);
1276
+ this.session.metadata.setValue(keyOf$1(this.pack), rest);
1277
+ }
1278
+ };
1279
+ //#endregion
1280
+ //#region src/host/interface/service.ts
1281
+ /** The packs of a world cannot be brought into a story because some of them have problems. */
1282
+ var InvalidPacksError = class extends Error {
1283
+ problems;
1284
+ constructor(message, problems) {
1285
+ super(message);
1286
+ this.problems = problems;
1287
+ }
1288
+ };
1289
+ const addressFor = (session) => (path) => `roleplay-api/sessions/interface/pack/${session}/${path.split("/").map(encodeURIComponent).join("/")}`;
1290
+ /** What the interface packs of the stories show and do, for the browser. */
1291
+ var InterfaceService = class {
1292
+ deps;
1293
+ keys = /* @__PURE__ */ new Map();
1294
+ keyOf = /* @__PURE__ */ new Map();
1295
+ constructor(deps) {
1296
+ this.deps = deps;
1297
+ }
1298
+ /** The key of a session's frames: the same for as long as the host runs, unguessable. */
1299
+ frameKey(session) {
1300
+ const known = this.keyOf.get(session);
1301
+ if (known !== void 0) return known;
1302
+ const key = randomBytes(24).toString("base64url");
1303
+ this.keyOf.set(session, key);
1304
+ this.keys.set(key, session);
1305
+ return key;
1306
+ }
1307
+ /** The session a frame key belongs to, if it is one the host made. */
1308
+ sessionOfFrame(key) {
1309
+ return this.keys.get(key);
1310
+ }
1311
+ sessions() {
1312
+ return join(this.deps.root(), "sessions");
1313
+ }
1314
+ session(id) {
1315
+ if (!isSessionId(id) || !existsSync(sessionDatabase(this.sessions(), id))) throw new SessionNotFoundError(`no session "${id}"`);
1316
+ return {
1317
+ folder: sessionFolder(this.sessions(), id),
1318
+ session: this.deps.open(id)
1319
+ };
1320
+ }
1321
+ /** The pack the session uses, read afresh. */
1322
+ active(id) {
1323
+ const { folder } = this.session(id);
1324
+ return activePack(folder, this.deps.root(), liveSettings(folder).interface.pack, () => addressFor(id));
1325
+ }
1326
+ describe(id) {
1327
+ const active = this.active(id);
1328
+ return {
1329
+ pack: active.pack === void 0 ? null : describePack(active.pack, this.frameKey(id)),
1330
+ problems: active.problems
1331
+ };
1332
+ }
1333
+ /** The player view, or that it is the one the caller has (`revision`). */
1334
+ view(id, revision) {
1335
+ const { folder, session } = this.session(id);
1336
+ const settings = liveSettings(folder);
1337
+ const view = playerViewOf(session, {
1338
+ zone: zoneOf(settings.clock),
1339
+ wall: (this.deps.wall ?? Date.now)()
1340
+ });
1341
+ return revision !== void 0 && revision === view.revision ? { unchanged: true } : { view };
1342
+ }
1343
+ /** 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. */
1344
+ async status(id) {
1345
+ const { folder, session } = this.session(id);
1346
+ const root = this.deps.root();
1347
+ const active = this.active(id);
1348
+ const choice = (base, from) => (name) => {
1349
+ const { pack, problems } = readPack(join(base, "ui", name), name, (file) => file);
1350
+ return {
1351
+ id: name,
1352
+ name: pack?.manifest.name ?? name,
1353
+ from,
1354
+ surfaces: pack === void 0 ? [] : Object.keys(pack.manifest.surfaces),
1355
+ problems
1356
+ };
1357
+ };
1358
+ const own = packIds(folder);
1359
+ const available = [...own.map(choice(folder, "story")), ...packIds(root).filter((name) => !own.includes(name)).map(choice(root, "root"))];
1360
+ const reference = session.metadata.get().world;
1361
+ const worldDirectory = reference === void 0 ? void 0 : await this.deps.worldDirectory(reference.id);
1362
+ return {
1363
+ setting: liveSettings(folder).interface.pack,
1364
+ ...active.pack === void 0 ? {} : { active: active.pack.id },
1365
+ problems: active.problems,
1366
+ available,
1367
+ ...worldDirectory === void 0 || reference === void 0 ? {} : { world: {
1368
+ name: reference.name,
1369
+ packs: worldPackStates(worldDirectory, folder).map(({ id: name, state }) => {
1370
+ const { pack, problems } = readPack(join(worldDirectory, "ui", name), name, (file) => file);
1371
+ return {
1372
+ id: name,
1373
+ name: pack?.manifest.name ?? name,
1374
+ state,
1375
+ problems
1376
+ };
1377
+ })
1378
+ } }
1379
+ };
1380
+ }
1381
+ /**
1382
+ * Brings the world's packs into the story, replacing a copy that differs (the old one goes to the story's `.trash`).
1383
+ * @throws {WorldNotFoundError} when the person no longer has the world.
1384
+ * @throws {InvalidPacksError} when a pack of the world has problems; nothing is changed then.
1385
+ */
1386
+ async sync(id) {
1387
+ const { folder, session } = this.session(id);
1388
+ const reference = session.metadata.get().world;
1389
+ const worldDirectory = reference === void 0 ? void 0 : await this.deps.worldDirectory(reference.id);
1390
+ if (worldDirectory === void 0) throw new WorldNotFoundError("the world this story was started from is not among your worlds any more");
1391
+ const { problems, ...result } = syncWorldPacks(worldDirectory, folder);
1392
+ if (problems.length > 0) throw new InvalidPacksError(`the interface packs of the world have ${problems.length} problem(s); nothing was changed`, problems);
1393
+ return result;
1394
+ }
1395
+ /** 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. */
1396
+ history(id, limit = PACK_LIMITS.history.fallback) {
1397
+ const { folder } = this.session(id);
1398
+ const timeline = readTimeline(folder);
1399
+ return pathTo(timeline, timeline.head).filter((node) => node.output !== void 0).map((node, index) => ({
1400
+ turn: index + 1,
1401
+ player: node.player,
1402
+ segments: (node.output?.segments ?? []).map((segment) => segment.type === "utterance" ? {
1403
+ type: "utterance",
1404
+ name: segment.name,
1405
+ text: segment.text
1406
+ } : {
1407
+ type: "narration",
1408
+ text: segment.text
1409
+ }),
1410
+ ...node.output?.ooc === void 0 ? {} : { note: node.output.ooc.note }
1411
+ })).slice(-Math.min(Math.max(1, limit), PACK_LIMITS.history.max));
1412
+ }
1413
+ /** 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
+ file(id, path) {
1415
+ const { pack } = this.active(id);
1416
+ const found = pack === void 0 ? void 0 : packFile(pack, path);
1417
+ if (found === void 0) return void 0;
1418
+ return found.mediaType.startsWith("text/html") ? {
1419
+ kind: "page",
1420
+ body: withBridge(readFileSync(found.file, "utf8")),
1421
+ mediaType: found.mediaType
1422
+ } : {
1423
+ kind: "file",
1424
+ ...found
1425
+ };
1426
+ }
1427
+ /** What the pack keeps in the session. @throws {RangeError} when a value does not fit. */
1428
+ storage(id, request) {
1429
+ const { session } = this.session(id);
1430
+ const { pack } = this.active(id);
1431
+ if (pack === void 0) throw new RangeError("the story uses no pack");
1432
+ const store = new PackStorage(session, pack.id);
1433
+ if (request.op === "get") return store.get(request.key);
1434
+ if (request.op === "set") store.set(request.key, request.value);
1435
+ else store.remove(request.key);
1436
+ return null;
1437
+ }
1438
+ /** Whether any pack with a tab exists in the root, a world or a story. */
1439
+ availability() {
1440
+ const root = this.deps.root();
1441
+ const inside = (folder) => existsSync(folder) ? readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join(folder, entry.name)) : [];
1442
+ return { tab: anyTab([
1443
+ root,
1444
+ ...inside(join(root, "worlds")),
1445
+ ...inside(join(root, "sessions"))
1446
+ ]) };
1447
+ }
1448
+ };
1449
+ //#endregion
1450
+ //#region src/host/interface/routes.ts
1451
+ /** The address under which the files of a session's pack are served to the page: `<prefix>/<session id>/<path of the file>`. */
1452
+ const PACK_FILES = "/sessions/interface/pack/";
1453
+ /**
1454
+ * The address under which a surface loads its own files: `<prefix>/<key>/<path of the file>`. A sandboxed frame has no
1455
+ * origin and so no cookie, so these are served without a login; the key is long, random and belongs to one story.
1456
+ */
1457
+ const FRAME_FILES = "/sessions/interface/frame/";
1458
+ const notFound = (res, error) => {
1459
+ if (error instanceof SessionNotFoundError || error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
1460
+ throw error;
1461
+ };
1462
+ function storageRequest(body) {
1463
+ if (typeof body !== "object" || body === null) return "the request must be an object";
1464
+ const { op, key, value } = body;
1465
+ if (op !== "get" && op !== "set" && op !== "remove") return "op must be get, set or remove";
1466
+ if (typeof key !== "string" || key === "") return "key must be text";
1467
+ return {
1468
+ op,
1469
+ key,
1470
+ ...value === void 0 ? {} : { value }
1471
+ };
1472
+ }
1473
+ function interfaceRoutes(api) {
1474
+ return {
1475
+ "/sessions/interface": { GET: async (_req, res, url) => {
1476
+ try {
1477
+ sendJson(res, 200, api.describe(url.searchParams.get("id") ?? ""));
1478
+ } catch (error) {
1479
+ notFound(res, error);
1480
+ }
1481
+ } },
1482
+ "/sessions/interface/view": { GET: async (_req, res, url) => {
1483
+ try {
1484
+ sendJson(res, 200, api.view(url.searchParams.get("id") ?? "", url.searchParams.get("revision") ?? void 0));
1485
+ } catch (error) {
1486
+ notFound(res, error);
1487
+ }
1488
+ } },
1489
+ "/sessions/interface/history": { GET: async (_req, res, url) => {
1490
+ const asked = Number(url.searchParams.get("limit"));
1491
+ try {
1492
+ sendJson(res, 200, api.history(url.searchParams.get("id") ?? "", Number.isInteger(asked) && asked > 0 ? asked : void 0));
1493
+ } catch (error) {
1494
+ notFound(res, error);
1495
+ }
1496
+ } },
1497
+ "/sessions/interface/storage": { POST: async (req, res, url) => {
1498
+ const request = storageRequest(await readJsonBody(req));
1499
+ if (typeof request === "string") return sendError(res, 400, request);
1500
+ try {
1501
+ sendJson(res, 200, { value: api.storage(url.searchParams.get("id") ?? "", request) });
1502
+ } catch (error) {
1503
+ if (error instanceof RangeError) return sendError(res, 422, error.message);
1504
+ notFound(res, error);
1505
+ }
1506
+ } },
1507
+ "/sessions/interface/status": { GET: async (_req, res, url) => {
1508
+ try {
1509
+ sendJson(res, 200, await api.status(url.searchParams.get("id") ?? ""));
1510
+ } catch (error) {
1511
+ notFound(res, error);
1512
+ }
1513
+ } },
1514
+ "/sessions/interface/sync": { POST: async (_req, res, url) => {
1515
+ try {
1516
+ sendJson(res, 200, await api.sync(url.searchParams.get("id") ?? ""));
1517
+ } catch (error) {
1518
+ if (error instanceof InvalidPacksError) return sendJson(res, 422, {
1519
+ message: error.message,
1520
+ problems: error.problems
1521
+ });
1522
+ notFound(res, error);
1523
+ }
1524
+ } },
1525
+ "/interface/availability": { GET: async (_req, res) => {
1526
+ sendJson(res, 200, api.availability());
1527
+ } }
1528
+ };
1529
+ }
1530
+ /** Serves one file of a session's pack, for a path like `/sessions/interface/pack/<id>/<file>` or `/sessions/interface/frame/<key>/<file>`. */
1531
+ async function sendPackFile(api, path, res) {
1532
+ const framed = path.startsWith(FRAME_FILES);
1533
+ const rest = path.slice((framed ? FRAME_FILES : PACK_FILES).length);
1534
+ const slash = rest.indexOf("/");
1535
+ if (slash <= 0) return sendError(res, 404, "not found");
1536
+ const session = framed ? api.sessionOfFrame(rest.slice(0, slash)) : rest.slice(0, slash);
1537
+ if (session === void 0) return sendError(res, 404, "not found");
1538
+ let file;
1539
+ try {
1540
+ file = api.file(session, rest.slice(slash + 1).split("/").map(decodeURIComponent).join("/"));
1541
+ } catch (error) {
1542
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
1543
+ if (error instanceof URIError) return sendError(res, 400, "the path is not valid");
1544
+ throw error;
1545
+ }
1546
+ if (file === void 0) return sendError(res, 404, "the pack has no such file");
1547
+ res.statusCode = 200;
1548
+ for (const [name, value] of Object.entries(PACK_HEADERS)) res.setHeader(name, value);
1549
+ res.setHeader("content-type", file.mediaType);
1550
+ if (framed) res.setHeader("access-control-allow-origin", "*");
1551
+ if (file.kind === "page") {
1552
+ const body = Buffer.from(file.body);
1553
+ res.setHeader("content-length", body.length);
1554
+ res.end(body);
1555
+ return;
1556
+ }
1557
+ res.setHeader("content-length", file.size);
1558
+ await pipeline(createReadStream(file.file), res);
1559
+ }
918
1560
  //#endregion
919
1561
  //#region src/host/http/api.ts
920
1562
  /** The largest picture that can be added to a gallery. */
@@ -966,7 +1608,7 @@ function languageField(value) {
966
1608
  throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
967
1609
  }
968
1610
  }
969
- function createApiHandler({ worlds, createWorld, authorWorld, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, connection, speech }) {
1611
+ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldCharacters, importer, avatars, worldFiles, worldEditor, sessions, packs, connection, speech }) {
970
1612
  const routes = {
971
1613
  "/speech/capabilities": { GET: async (_req, res) => {
972
1614
  sendJson(res, 200, { streaming: speech.streaming() });
@@ -1007,6 +1649,22 @@ function createApiHandler({ worlds, createWorld, authorWorld, worldCharacters, i
1007
1649
  }
1008
1650
  }
1009
1651
  },
1652
+ "/worlds/starter": {
1653
+ GET: async (_req, res) => {
1654
+ sendJson(res, 200, await starter.list());
1655
+ },
1656
+ POST: async (req, res) => {
1657
+ const body = await readJsonBody(req);
1658
+ if (typeof body.folder !== "string") return sendError(res, 400, "folder must be text");
1659
+ try {
1660
+ sendJson(res, 201, await starter.add(body.folder));
1661
+ } catch (error) {
1662
+ if (error instanceof UnknownStarterError) return sendError(res, 404, error.message);
1663
+ if (error instanceof WorldFolderExistsError) return sendError(res, 409, error.message);
1664
+ throw error;
1665
+ }
1666
+ }
1667
+ },
1010
1668
  "/worlds/import/card": { POST: async (req, res, url) => {
1011
1669
  const name = decodeURIComponent(String(req.headers["x-file-name"] ?? url.searchParams.get("name") ?? "card"));
1012
1670
  try {
@@ -1383,6 +2041,19 @@ function createApiHandler({ worlds, createWorld, authorWorld, worldCharacters, i
1383
2041
  return sendError(res, 409, error instanceof Error ? error.message : String(error));
1384
2042
  }
1385
2043
  } },
2044
+ "/worlds/state/character/portrait/upload": { POST: async (req, res, url) => {
2045
+ const name = decodeURIComponent(String(req.headers["x-file-name"] ?? "portrait.png"));
2046
+ try {
2047
+ sendJson(res, 200, await worldEditor.uploadPortrait(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? "", await readBinaryBody(req, MAX_UPLOAD_BYTES), name));
2048
+ } catch (error) {
2049
+ if (error instanceof WorldNotFoundError) return sendError(res, 404, error.message);
2050
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2051
+ message: error.message,
2052
+ problems: error.problems
2053
+ });
2054
+ throw error;
2055
+ }
2056
+ } },
1386
2057
  "/worlds/state/character/portrait/file": { GET: async (_req, res, url) => {
1387
2058
  try {
1388
2059
  await sendImage(res, await worldEditor.portraitFile(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? ""));
@@ -1707,6 +2378,19 @@ function createApiHandler({ worlds, createWorld, authorWorld, worldCharacters, i
1707
2378
  return sendError(res, 409, error instanceof Error ? error.message : String(error));
1708
2379
  }
1709
2380
  } },
2381
+ "/sessions/world/character/portrait/upload": { POST: async (req, res, url) => {
2382
+ const name = decodeURIComponent(String(req.headers["x-file-name"] ?? "portrait.png"));
2383
+ try {
2384
+ sendJson(res, 200, await sessions.uploadPortrait(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? "", await readBinaryBody(req, MAX_UPLOAD_BYTES), name));
2385
+ } catch (error) {
2386
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2387
+ if (error instanceof InvalidEditProblems) return sendJson(res, 422, {
2388
+ message: error.message,
2389
+ problems: error.problems
2390
+ });
2391
+ throw error;
2392
+ }
2393
+ } },
1710
2394
  "/sessions/world/character/portrait/file": { GET: async (_req, res, url) => {
1711
2395
  try {
1712
2396
  await sendImage(res, await sessions.portraitFile(url.searchParams.get("id") ?? "", url.searchParams.get("key") ?? ""));
@@ -1714,6 +2398,27 @@ function createApiHandler({ worlds, createWorld, authorWorld, worldCharacters, i
1714
2398
  return sendError(res, 404, error instanceof Error ? error.message : String(error));
1715
2399
  }
1716
2400
  } },
2401
+ "/sessions/activity/run": { GET: async (_req, res, url) => {
2402
+ try {
2403
+ const detail = sessions.activityRun(url.searchParams.get("id") ?? "", url.searchParams.get("run") ?? "");
2404
+ if (detail === void 0) return sendError(res, 404, "this run was not kept, or has been dropped to make room");
2405
+ sendJson(res, 200, detail);
2406
+ } catch (error) {
2407
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2408
+ if (error instanceof RangeError) return sendError(res, 400, error.message);
2409
+ throw error;
2410
+ }
2411
+ } },
2412
+ "/sessions/vectors/reset": { POST: async (_req, res, url) => {
2413
+ try {
2414
+ sessions.resetVectors(url.searchParams.get("id") ?? "");
2415
+ } catch (error) {
2416
+ if (error instanceof SessionNotFoundError) return sendError(res, 404, error.message);
2417
+ throw error;
2418
+ }
2419
+ res.statusCode = 204;
2420
+ res.end();
2421
+ } },
1717
2422
  "/sessions/rename": { POST: async (req, res, url) => {
1718
2423
  const body = await readJsonBody(req);
1719
2424
  const name = typeof body === "object" && body !== null ? body.name : void 0;
@@ -1740,6 +2445,7 @@ function createApiHandler({ worlds, createWorld, authorWorld, worldCharacters, i
1740
2445
  res.statusCode = 204;
1741
2446
  res.end();
1742
2447
  } },
2448
+ ...interfaceRoutes(packs),
1743
2449
  "/worlds/cover": { GET: async (_req, res, url) => {
1744
2450
  const cover = await worlds.cover(url.searchParams.get("id") ?? "");
1745
2451
  if (cover === void 0) return sendError(res, 404, "no cover");
@@ -1752,14 +2458,24 @@ function createApiHandler({ worlds, createWorld, authorWorld, worldCharacters, i
1752
2458
  } }
1753
2459
  };
1754
2460
  return async (req, res) => {
1755
- const rejection = connection.requestRejection(req);
2461
+ const url = new URL(req.url ?? "/", "http://localhost");
2462
+ const path = url.pathname.slice(`/roleplay-api`.length) || "/";
2463
+ const framed = path.startsWith("/sessions/interface/frame/") && req.method === "GET";
2464
+ const rejection = framed ? void 0 : connection.requestRejection(req);
1756
2465
  if (rejection !== void 0) {
1757
2466
  res.statusCode = rejection;
1758
2467
  res.end();
1759
2468
  return;
1760
2469
  }
1761
- const url = new URL(req.url ?? "/", "http://localhost");
1762
- const path = url.pathname.slice(`/roleplay-api`.length) || "/";
2470
+ if ((path.startsWith("/sessions/interface/pack/") || framed) && req.method === "GET") {
2471
+ try {
2472
+ await sendPackFile(packs, path, res);
2473
+ } catch (error) {
2474
+ if (res.headersSent) res.destroy();
2475
+ else sendError(res, 500, error instanceof Error ? error.message : "internal error");
2476
+ }
2477
+ return;
2478
+ }
1763
2479
  const methods = routes[path];
1764
2480
  if (methods === void 0) return sendError(res, 404, "not found");
1765
2481
  const route = methods[req.method ?? ""];
@@ -2461,7 +3177,13 @@ function editWorldPlace(deps, id, key, edit) {
2461
3177
  if (place === void 0) throw new InvalidEditProblems([`there is no place "${key}"`]);
2462
3178
  try {
2463
3179
  session.transaction(() => {
2464
- const { visualIdentity, ...patch } = edit;
3180
+ const { visualIdentity, parent, ...rest } = edit;
3181
+ const container = parent === void 0 ? void 0 : parent === null ? null : session.locations.list().find((candidate) => (candidate.sourceId ?? String(candidate.id)) === parent)?.id;
3182
+ if (container === void 0 && parent !== void 0) throw new InvalidEditProblems([`there is no place "${parent}" to put it in`]);
3183
+ const patch = {
3184
+ ...rest,
3185
+ ...container === void 0 ? {} : { parentId: container }
3186
+ };
2465
3187
  if (Object.keys(patch).length > 0) session.locations.update(place.id, patch);
2466
3188
  if (visualIdentity === null) session.visualIdentities.remove("location", place.id);
2467
3189
  else if (visualIdentity !== void 0) session.visualIdentities.set("location", place.id, visualIdentity);
@@ -2478,10 +3200,13 @@ function editWorldThing(deps, id, key, edit) {
2478
3200
  if (item === void 0) throw new InvalidEditProblems([`there is no thing "${key}"`]);
2479
3201
  try {
2480
3202
  session.transaction(() => {
2481
- const { visualIdentity, containerState, ...patch } = edit;
3203
+ const { visualIdentity, containerState, owner, ...patch } = edit;
3204
+ const holder = owner === void 0 ? void 0 : owner === null ? null : session.characters.list().find((candidate) => (candidate.sourceId ?? String(candidate.id)) === owner)?.id;
3205
+ if (holder === void 0 && owner !== void 0) throw new InvalidEditProblems([`there is no character "${owner}" to own it`]);
2482
3206
  const changes = {
2483
3207
  ...patch,
2484
- ...containerState === void 0 ? {} : { container: { state: containerState } }
3208
+ ...containerState === void 0 ? {} : { container: { state: containerState } },
3209
+ ...holder === void 0 ? {} : { ownerId: holder }
2485
3210
  };
2486
3211
  if (Object.keys(changes).length > 0) session.items.update(item.id, changes);
2487
3212
  if (visualIdentity === null) session.visualIdentities.remove("item", item.id);
@@ -2647,6 +3372,28 @@ async function generateSessionCharacterPortrait(deps, id, key, service) {
2647
3372
  });
2648
3373
  return worldOf(session, deps.sessionsDir());
2649
3374
  }
3375
+ /** The picture the player brought becomes the session character's portrait. */
3376
+ async function uploadSessionCharacterPortrait(deps, id, key, png, originalName) {
3377
+ const session = sessionOf(deps, id);
3378
+ const character = characterOf(session, key);
3379
+ const identity = session.visualIdentities.get("character", character.id);
3380
+ try {
3381
+ await uploadReferenceImage({
3382
+ root: sessionFolder(deps.sessionsDir(), id),
3383
+ subject: {
3384
+ kind: "character",
3385
+ localId: character.sourceId ?? character.id,
3386
+ name: character.name,
3387
+ ...identity?.globalId === void 0 ? {} : { globalId: identity.globalId }
3388
+ },
3389
+ png,
3390
+ ...originalName === void 0 ? {} : { originalName }
3391
+ });
3392
+ } catch (error) {
3393
+ throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
3394
+ }
3395
+ return worldOf(session, deps.sessionsDir());
3396
+ }
2650
3397
  /** Resolve a portrait through session state so request parameters cannot select arbitrary files. */
2651
3398
  async function sessionCharacterPortraitFile(deps, id, key) {
2652
3399
  const session = sessionOf(deps, id);
@@ -2833,6 +3580,7 @@ function infoOf(document) {
2833
3580
  authorUrl: textOf(author["url"]),
2834
3581
  timeZone: textOf(document["time_zone"]),
2835
3582
  startingTime: textOf(document["starting_time"]),
3583
+ version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
2836
3584
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
2837
3585
  title: textOf(entry["title"]),
2838
3586
  text: entry["text"]
@@ -2887,6 +3635,7 @@ async function editWorldInfo(directory, edit) {
2887
3635
  }
2888
3636
  if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
2889
3637
  if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
3638
+ if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
2890
3639
  if (edit.alternateOpenings !== void 0) {
2891
3640
  if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
2892
3641
  else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
@@ -2908,6 +3657,15 @@ async function editWorldInfo(directory, edit) {
2908
3657
  * @throws {InvalidStartError} when the name or the player's character is not acceptable.
2909
3658
  * @throws {AgentUnavailableError} when the chat cannot be created.
2910
3659
  */
3660
+ /** What is unfinished in the world as it was started, errors first, for the player's card before the first message. */
3661
+ function worldFindings(session) {
3662
+ const rank = {
3663
+ error: 0,
3664
+ warning: 1,
3665
+ info: 2
3666
+ };
3667
+ return lintWorld(session).filter((finding) => finding.severity !== "info").sort((a, b) => rank[a.severity] - rank[b.severity]).map((finding) => finding.message);
3668
+ }
2911
3669
  async function startSession(deps, request) {
2912
3670
  const world = await deps.worlds.find(request.worldId);
2913
3671
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${request.worldId}"`);
@@ -2958,6 +3716,7 @@ async function startSession(deps, request) {
2958
3716
  world: {
2959
3717
  id: world.summary.id,
2960
3718
  name: world.summary.name,
3719
+ ...world.summary.version === void 0 ? {} : { version: world.summary.version },
2961
3720
  source: `worlds/${world.folder}`
2962
3721
  }
2963
3722
  });
@@ -2988,7 +3747,10 @@ async function startSession(deps, request) {
2988
3747
  if (avatars !== void 0) for (const entry of brought) await copyPortrait(avatars, entry.from, entry.document, sessionFolder(sessionsDir, id), entry.id);
2989
3748
  const promptProblems = copyWorldPrompts(world.directory, sessionFolder(sessionsDir, id));
2990
3749
  if (promptProblems.length > 0) throw new InvalidWorldError(`the prompts of "${world.summary.name}" have ${promptProblems.length} problem(s)`, promptProblems);
3750
+ const packProblems = copyWorldPacks(world.directory, sessionFolder(sessionsDir, id));
3751
+ if (packProblems.length > 0) throw new InvalidWorldError(`the interface packs of "${world.summary.name}" have ${packProblems.length} problem(s)`, packProblems);
2991
3752
  writeSettings(sessionFolder(sessionsDir, id), settings);
3753
+ addToNote(session, "world", 1, worldFindings(session));
2992
3754
  chatSessionId = await deps.agent.ensure(id, name, opening);
2993
3755
  } catch (error) {
2994
3756
  deps.state.deleteSession(sessionsDir, id);
@@ -3131,10 +3893,49 @@ function payloadOf(deps, id, settings) {
3131
3893
  bounds: SETTINGS_SPEC,
3132
3894
  pendingRecords: deps.pendingRecords(id),
3133
3895
  pendingConsolidation: deps.pendingConsolidation(id),
3896
+ activity: deps.activity(id),
3897
+ interventions: deps.interventions(id),
3898
+ vectors: deps.vectors(id),
3134
3899
  ...clockMode === void 0 ? {} : { clockMode }
3135
3900
  };
3136
3901
  }
3137
3902
  //#endregion
3903
+ //#region src/host/sessions/vectors.ts
3904
+ /** How many waiting texts are counted before saying "that many": the number is for reassurance, not accounting. */
3905
+ const MAX_COUNTED = 1e4;
3906
+ function vectorStatus(session) {
3907
+ const info = session.recallIndex.info();
3908
+ return {
3909
+ available: session.recallIndex.vectors.available,
3910
+ ...info === void 0 ? {
3911
+ embedded: 0,
3912
+ pending: session.recallIndex.pending(MAX_COUNTED).length
3913
+ } : {
3914
+ model: info.model,
3915
+ dimensions: info.dimensions,
3916
+ embedded: info.embedded,
3917
+ pending: info.pending
3918
+ }
3919
+ };
3920
+ }
3921
+ /** Forgets the stored vectors; the texts stay and are embedded again, by the model now selected, the next time the story searches. */
3922
+ function resetVectors(session) {
3923
+ session.recallIndex.reset();
3924
+ }
3925
+ //#endregion
3926
+ //#region src/host/sessions/interventions.ts
3927
+ /** What the story's triggers delivered lately and what became of each, oldest first. */
3928
+ 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
+ }));
3937
+ }
3938
+ //#endregion
3138
3939
  //#region src/host/sessions/open-session.ts
3139
3940
  /** Make sure a session has its DSH chat, so that it can be opened. */
3140
3941
  async function openSession(deps, id) {
@@ -3387,7 +4188,8 @@ async function loadWorld(folder, dir, file, problems) {
3387
4188
  name: world.name,
3388
4189
  description: world.description,
3389
4190
  tags: world.tags,
3390
- ...world.author === void 0 ? {} : { author: world.author }
4191
+ ...world.author === void 0 ? {} : { author: world.author },
4192
+ ...world.version === void 0 ? {} : { version: world.version }
3391
4193
  },
3392
4194
  ...world.opening === void 0 ? {} : { opening: world.opening },
3393
4195
  ...world.clock === void 0 ? {} : { clock: world.clock },
@@ -3641,7 +4443,10 @@ function apply(ctx, config) {
3641
4443
  sessionsDir: () => join(root.path, "sessions"),
3642
4444
  pendingRecords: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).pendingCommits.list().length,
3643
4445
  clockMode: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).clock.get()?.mode,
3644
- pendingConsolidation: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).consolidation.pending().length
4446
+ pendingConsolidation: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).consolidation.pending().length,
4447
+ vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4448
+ activity: (id) => readActivity(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
4449
+ interventions: (id) => readInterventions(ctx.roleplayState.openSession(join(root.path, "sessions"), id))
3645
4450
  };
3646
4451
  const purgeChat = purgeOf(ctx, config.sessionStorePath);
3647
4452
  const deps = {
@@ -3652,6 +4457,11 @@ function apply(ctx, config) {
3652
4457
  avatars: () => avatarsWorld(root.path)
3653
4458
  };
3654
4459
  registerApi(ctx, {
4460
+ packs: new InterfaceService({
4461
+ open: (id) => ctx.roleplayState.openSession(deps.sessionsDir(), id),
4462
+ root: () => root.path,
4463
+ worldDirectory: async (worldId) => (await worlds.find(worldId))?.directory
4464
+ }),
3655
4465
  speech: {
3656
4466
  voices: async () => await voicesOf(textToSpeechOf(ctx)),
3657
4467
  speak: async (parts) => await speakParts(textToSpeechOf(ctx), parts),
@@ -3659,6 +4469,10 @@ function apply(ctx, config) {
3659
4469
  },
3660
4470
  worlds,
3661
4471
  createWorld: (input) => createWorld(worlds, input),
4472
+ starter: {
4473
+ list: () => listStarterWorlds(worlds),
4474
+ add: (folder) => addStarterWorld(worlds, folder)
4475
+ },
3662
4476
  authorWorld: async (worldId, title, language) => {
3663
4477
  const world = await worlds.find(worldId);
3664
4478
  if (world === void 0) throw new WorldNotFoundError(`there is no world with id "${worldId}"`);
@@ -3733,7 +4547,8 @@ function apply(ctx, config) {
3733
4547
  editRelation: async (worldId, edit) => await editWorldRelation$1(await editableWorld(worlds, worldId, root.path), edit),
3734
4548
  editNarrationVoice: async (worldId, voice) => await editWorldNarrationVoice(await editableWorld(worlds, worldId, root.path), voice),
3735
4549
  generatePortrait: async (worldId, key) => await generateWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, imageGenerationOf(ctx)),
3736
- portraitFile: async (worldId, key) => await worldCharacterPortraitFile(await editableWorld(worlds, worldId, root.path), key)
4550
+ portraitFile: async (worldId, key) => await worldCharacterPortraitFile(await editableWorld(worlds, worldId, root.path), key),
4551
+ uploadPortrait: async (worldId, key, png, name) => await uploadWorldCharacterPortrait(await editableWorld(worlds, worldId, root.path), key, png, name)
3737
4552
  },
3738
4553
  sessions: {
3739
4554
  list: () => listSessions(deps),
@@ -3797,6 +4612,10 @@ function apply(ctx, config) {
3797
4612
  state: ctx.roleplayState,
3798
4613
  sessionsDir: deps.sessionsDir
3799
4614
  }, id, key),
4615
+ uploadPortrait: (id, key, png, name) => uploadSessionCharacterPortrait({
4616
+ state: ctx.roleplayState,
4617
+ sessionsDir: deps.sessionsDir
4618
+ }, id, key, png, name),
3800
4619
  world: (id) => readWorldState({
3801
4620
  state: ctx.roleplayState,
3802
4621
  sessionsDir: deps.sessionsDir
@@ -3810,6 +4629,16 @@ function apply(ctx, config) {
3810
4629
  writeSettings: (id, value) => writeChatSettings(settingsDeps, id, value),
3811
4630
  timeline: (id) => timelinesOf(ctx, deps.sessionsDir, id).view(id),
3812
4631
  moveTimeline: (id, to) => timelinesOf(ctx, deps.sessionsDir, id).move(chatSessionId(id), to === "start" ? null : to),
4632
+ activityRun: (id, run) => {
4633
+ const sessions = join(root.path, "sessions");
4634
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
4635
+ return readRunDetail(sessionFolder(sessions, id), run);
4636
+ },
4637
+ resetVectors: (id) => {
4638
+ const sessions = join(root.path, "sessions");
4639
+ if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
4640
+ resetVectors(ctx.roleplayState.openSession(sessions, id));
4641
+ },
3813
4642
  notes: (id) => notesOfSession({
3814
4643
  sessionsDir: deps.sessionsDir,
3815
4644
  open: (sessionId) => ctx.roleplayState.openSession(deps.sessionsDir(), sessionId)