@dsh-agentic-roleplay/core 0.1.1 → 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.
- package/README.md +1 -1
- package/lib/{activity-BbqFG9-3.js → activity-t7OBgHlc.js} +255 -61
- package/lib/authoring.js +295 -14
- package/lib/client.js +1896 -453
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +1 -1
- package/lib/{documents-ZVoUTnD2.js → documents-Bu5uYRZB.js} +3 -3
- package/lib/{gallery-KGCdeCnM.js → gallery-DUeBMHQX.js} +2 -2
- package/lib/{generator-NYnNdpWb.js → generator-HPifO3Kk.js} +125 -20
- package/lib/images.js +3 -3
- package/lib/index.js +638 -14
- package/lib/{narration-DcnCqA1l.js → narration-BRyHU0H2.js} +10 -4
- package/lib/orchestration.js +303 -161
- package/lib/packs-ByP1J-zj.js +1334 -0
- package/lib/{presenter-agent-7j1c7QEz.js → presenter-agent-G43ODV8I.js} +3 -3
- package/package.json +4 -3
- package/prompts/en/roleplay/ask-answerer.md +3 -0
- package/prompts/en/roleplay/ask-question.md +2 -0
- package/prompts/en/roleplay/character-decide.md +1 -1
- package/prompts/en/roleplay/character-lookup.md +1 -1
- package/prompts/en/roleplay/game-master.md +5 -1
- package/prompts/en/roleplay/ooc-empty.md +1 -1
- package/prompts/en/world/procedure.md +1 -1
- package/prompts/zh/roleplay/ask-answerer.md +3 -0
- package/prompts/zh/roleplay/ask-question.md +2 -0
- package/prompts/zh/roleplay/character-decide.md +1 -1
- package/prompts/zh/roleplay/character-lookup.md +1 -1
- package/prompts/zh/roleplay/game-master.md +5 -1
- package/prompts/zh/roleplay/ooc-empty.md +1 -1
- package/prompts/zh/world/procedure.md +1 -1
- package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
- package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
- package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
- package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
- package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
- package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
- package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
- package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
- package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
- package/lib/worlds-DYgjdH8O.js +0 -504
package/lib/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
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-
|
|
3
|
-
import { C as
|
|
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-
|
|
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";
|
|
5
5
|
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-
|
|
7
|
-
import {
|
|
8
|
-
import { i as updateImage, n as galleryFile, r as listGallery } from "./gallery-
|
|
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";
|
|
@@ -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 { 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";
|
|
@@ -982,6 +982,581 @@ async function readBinaryBody(req, limit) {
|
|
|
982
982
|
if (size === 0) throw new HttpError(400, "the upload is empty");
|
|
983
983
|
return Buffer.concat(chunks);
|
|
984
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
|
+
}
|
|
985
1560
|
//#endregion
|
|
986
1561
|
//#region src/host/http/api.ts
|
|
987
1562
|
/** The largest picture that can be added to a gallery. */
|
|
@@ -1033,7 +1608,7 @@ function languageField(value) {
|
|
|
1033
1608
|
throw new InvalidEditProblems([error instanceof Error ? error.message : String(error)]);
|
|
1034
1609
|
}
|
|
1035
1610
|
}
|
|
1036
|
-
function createApiHandler({ worlds, createWorld, starter, 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 }) {
|
|
1037
1612
|
const routes = {
|
|
1038
1613
|
"/speech/capabilities": { GET: async (_req, res) => {
|
|
1039
1614
|
sendJson(res, 200, { streaming: speech.streaming() });
|
|
@@ -1823,6 +2398,17 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
|
|
|
1823
2398
|
return sendError(res, 404, error instanceof Error ? error.message : String(error));
|
|
1824
2399
|
}
|
|
1825
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
|
+
} },
|
|
1826
2412
|
"/sessions/vectors/reset": { POST: async (_req, res, url) => {
|
|
1827
2413
|
try {
|
|
1828
2414
|
sessions.resetVectors(url.searchParams.get("id") ?? "");
|
|
@@ -1859,6 +2445,7 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
|
|
|
1859
2445
|
res.statusCode = 204;
|
|
1860
2446
|
res.end();
|
|
1861
2447
|
} },
|
|
2448
|
+
...interfaceRoutes(packs),
|
|
1862
2449
|
"/worlds/cover": { GET: async (_req, res, url) => {
|
|
1863
2450
|
const cover = await worlds.cover(url.searchParams.get("id") ?? "");
|
|
1864
2451
|
if (cover === void 0) return sendError(res, 404, "no cover");
|
|
@@ -1871,14 +2458,24 @@ function createApiHandler({ worlds, createWorld, starter, authorWorld, worldChar
|
|
|
1871
2458
|
} }
|
|
1872
2459
|
};
|
|
1873
2460
|
return async (req, res) => {
|
|
1874
|
-
const
|
|
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);
|
|
1875
2465
|
if (rejection !== void 0) {
|
|
1876
2466
|
res.statusCode = rejection;
|
|
1877
2467
|
res.end();
|
|
1878
2468
|
return;
|
|
1879
2469
|
}
|
|
1880
|
-
|
|
1881
|
-
|
|
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
|
+
}
|
|
1882
2479
|
const methods = routes[path];
|
|
1883
2480
|
if (methods === void 0) return sendError(res, 404, "not found");
|
|
1884
2481
|
const route = methods[req.method ?? ""];
|
|
@@ -3150,6 +3747,8 @@ async function startSession(deps, request) {
|
|
|
3150
3747
|
if (avatars !== void 0) for (const entry of brought) await copyPortrait(avatars, entry.from, entry.document, sessionFolder(sessionsDir, id), entry.id);
|
|
3151
3748
|
const promptProblems = copyWorldPrompts(world.directory, sessionFolder(sessionsDir, id));
|
|
3152
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);
|
|
3153
3752
|
writeSettings(sessionFolder(sessionsDir, id), settings);
|
|
3154
3753
|
addToNote(session, "world", 1, worldFindings(session));
|
|
3155
3754
|
chatSessionId = await deps.agent.ensure(id, name, opening);
|
|
@@ -3295,6 +3894,7 @@ function payloadOf(deps, id, settings) {
|
|
|
3295
3894
|
pendingRecords: deps.pendingRecords(id),
|
|
3296
3895
|
pendingConsolidation: deps.pendingConsolidation(id),
|
|
3297
3896
|
activity: deps.activity(id),
|
|
3897
|
+
interventions: deps.interventions(id),
|
|
3298
3898
|
vectors: deps.vectors(id),
|
|
3299
3899
|
...clockMode === void 0 ? {} : { clockMode }
|
|
3300
3900
|
};
|
|
@@ -3323,6 +3923,19 @@ function resetVectors(session) {
|
|
|
3323
3923
|
session.recallIndex.reset();
|
|
3324
3924
|
}
|
|
3325
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
|
|
3326
3939
|
//#region src/host/sessions/open-session.ts
|
|
3327
3940
|
/** Make sure a session has its DSH chat, so that it can be opened. */
|
|
3328
3941
|
async function openSession(deps, id) {
|
|
@@ -3832,7 +4445,8 @@ function apply(ctx, config) {
|
|
|
3832
4445
|
clockMode: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).clock.get()?.mode,
|
|
3833
4446
|
pendingConsolidation: (id) => ctx.roleplayState.openSession(join(root.path, "sessions"), id).consolidation.pending().length,
|
|
3834
4447
|
vectors: (id) => vectorStatus(ctx.roleplayState.openSession(join(root.path, "sessions"), id)),
|
|
3835
|
-
activity: (id) => readActivity(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))
|
|
3836
4450
|
};
|
|
3837
4451
|
const purgeChat = purgeOf(ctx, config.sessionStorePath);
|
|
3838
4452
|
const deps = {
|
|
@@ -3843,6 +4457,11 @@ function apply(ctx, config) {
|
|
|
3843
4457
|
avatars: () => avatarsWorld(root.path)
|
|
3844
4458
|
};
|
|
3845
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
|
+
}),
|
|
3846
4465
|
speech: {
|
|
3847
4466
|
voices: async () => await voicesOf(textToSpeechOf(ctx)),
|
|
3848
4467
|
speak: async (parts) => await speakParts(textToSpeechOf(ctx), parts),
|
|
@@ -4010,6 +4629,11 @@ function apply(ctx, config) {
|
|
|
4010
4629
|
writeSettings: (id, value) => writeChatSettings(settingsDeps, id, value),
|
|
4011
4630
|
timeline: (id) => timelinesOf(ctx, deps.sessionsDir, id).view(id),
|
|
4012
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
|
+
},
|
|
4013
4637
|
resetVectors: (id) => {
|
|
4014
4638
|
const sessions = join(root.path, "sessions");
|
|
4015
4639
|
if (!isSessionId(id) || !existsSync(sessionDatabase(sessions, id))) throw new SessionNotFoundError(`no session "${id}"`);
|