@dsh-agentic-roleplay/core 0.7.2 → 0.8.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/authoring-tools-DNnx0Nts.js +3574 -0
- package/lib/authoring.js +295 -333
- package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
- package/lib/client.js +931 -415
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +2 -2
- package/lib/doctor.js +2 -2
- package/lib/{gallery-BxZGOgMb.js → gallery-D9nG3C78.js} +2 -2
- package/lib/{generator-BFmSYvR8.js → generator-r1Czm7oi.js} +2 -2
- package/lib/helper.js +1 -1
- package/lib/{hooks-HnqXO8mM.js → hooks-BQCzgggH.js} +92 -8
- package/lib/images.js +4 -4
- package/lib/index.js +1326 -1638
- package/lib/{library-BGxPKs9a.js → library-zI-2tG7h.js} +59 -9
- package/lib/{lorebook-author-tools-D9RrMK5g.js → lorebook-author-tools-ywaYicwd.js} +7 -7
- package/lib/lorebook-authoring.js +4 -4
- package/lib/{narration-DvFBqmqe.js → narration-CnBlVure.js} +52 -8
- package/lib/orchestration.js +95 -18
- package/lib/{pack-jail-MPekqSuQ.js → pack-jail-5EJ-WYyW.js} +1274 -69
- package/lib/{packs-jowC-MN_.js → packs-Cv8hanXJ.js} +2 -2
- package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-BSaMSd3G.js} +6 -6
- package/lib/{preset-VatN-845.js → preset-CWI3-0r1.js} +4 -3
- package/lib/{preset-author-tools-8kv1Glxe.js → preset-author-tools-BrJYa2cr.js} +7 -7
- package/lib/preset-authoring.js +5 -5
- package/lib/presets-MwOSMMyu.js +3998 -0
- package/lib/{reflection-CvOZGjmn.js → reflection-zSaMsjKj.js} +127 -127
- package/lib/{text-JbWfTHbr.js → text-BzudpQLS.js} +11 -1
- package/lib/{turn-guard-BvCs1VxB.js → turn-guard-Cv8pfHEA.js} +6 -2
- package/package.json +2 -2
- package/prompts/en/import/casting.md +14 -0
- package/prompts/en/import/classifier.md +9 -0
- package/prompts/en/import/finish-draft.md +1 -0
- package/prompts/en/import/generator.md +8 -0
- package/prompts/en/import/notice-repair.md +4 -0
- package/prompts/en/import/repair-again.md +3 -0
- package/prompts/en/import/roster.md +1 -0
- package/prompts/en/import/variables.md +1 -0
- package/prompts/en/roleplay/game-master.md +3 -0
- package/prompts/en/roleplay/standing.md +1 -0
- package/prompts/en/world/author.md +1 -1
- package/prompts/zh/import/casting.md +14 -0
- package/prompts/zh/import/classifier.md +9 -0
- package/prompts/zh/import/finish-draft.md +1 -0
- package/prompts/zh/import/generator.md +8 -0
- package/prompts/zh/import/notice-repair.md +4 -0
- package/prompts/zh/import/repair-again.md +3 -0
- package/prompts/zh/import/roster.md +1 -0
- package/prompts/zh/import/variables.md +1 -0
- package/prompts/zh/roleplay/game-master.md +3 -0
- package/prompts/zh/roleplay/standing.md +1 -0
- package/prompts/zh/world/author.md +1 -1
- package/lib/authoring-tools-q34iq3hW.js +0 -6140
- package/lib/route-DRTJ_vcA.js +0 -518
|
@@ -0,0 +1,3574 @@
|
|
|
1
|
+
import "./access-DtOxFKBK.js";
|
|
2
|
+
import { A as isLeftOut, At as DEFAULT_SLOTS, C as pruneMembers, D as classifyItems, Dt as LORE_KINDS, E as buildRoster, G as withPlayer, H as cleanText, K as IMPORT_FOLDER, M as askYesNo, Ot as LORE_SCOPES, Q as readImportFolder, S as pruneLoreSubjects, U as itemise, X as openingText, Y as PICTURE_FILE, _ as extractStyle, _t as parseCharacterFile, a as isPresetName, at as variableProblems, b as pruneKnowledge, bt as InvalidEditProblems, ct as LOCATION_FILE_NAME, dt as SLOTS_FILE_NAME, ft as parseItemFile, g as extractEntities, gt as CHARACTER_FILE_NAME, h as emptyExtracted, ht as parseFactionFile, k as ROLES, kt as WEEKDAY_NAMES, lt as parseLocationFile, mt as FACTION_FILE_NAME, nt as VARIABLES_FILE_NAME, ot as LORE_FILE_NAME, pt as parseSlotsFile, rt as loadVariables, st as parseLoreFile, tt as parseImportCommand, ut as ITEM_FILE_NAME, vt as readVariableValues, w as pruneRelationships, x as pruneLinks, y as extractVariables, yt as readIdentifier } from "./presets-MwOSMMyu.js";
|
|
3
|
+
import { l as atomicWrite, m as parseSwitchboard, u as atomicWriteJson } from "./narration-CnBlVure.js";
|
|
4
|
+
import { G as commandFlagKey, K as readDocument, U as plotReferenceProblems, V as loadPlots, Y as errorMessage, Z as PROMPTS_FOLDER, a as externalWithheld, it as shippedLanguages, lt as InvalidWorldError, q as Reader, r as externalGiven, rt as promptProblem, t as externalToolLimit } from "./hooks-BQCzgggH.js";
|
|
5
|
+
import { t as trimCharacters } from "./text-BzudpQLS.js";
|
|
6
|
+
import { c as runChild, h as currentTurn, s as namedModel, t as ChildTimeoutError, u as parseSampling } from "./child-D6mpkkCE.js";
|
|
7
|
+
import { C as trOf, _ as writeImageFileMetadata, b as mapLimit, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as uniqueKey, x as norm } from "./library-zI-2tG7h.js";
|
|
8
|
+
import { dirname, join, relative } from "node:path";
|
|
9
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
12
|
+
import { createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
13
|
+
import { inflateSync } from "node:zlib";
|
|
14
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
15
|
+
import { Service } from "@deepseek-ai/cordis";
|
|
16
|
+
import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
|
|
17
|
+
import { lookup } from "node:dns";
|
|
18
|
+
import { request } from "node:http";
|
|
19
|
+
import { request as request$1 } from "node:https";
|
|
20
|
+
import { BlockList, isIP } from "node:net";
|
|
21
|
+
//#region src/shared/authoring-chat.ts
|
|
22
|
+
const PREFIX = "world-author-";
|
|
23
|
+
/** Stable DSH chat identity for the authoring conversation of one world. */
|
|
24
|
+
function authoringChatSessionId(worldId) {
|
|
25
|
+
if (worldId === "") throw new TypeError("world id cannot be empty");
|
|
26
|
+
return `${PREFIX}${encodeURIComponent(worldId)}`;
|
|
27
|
+
}
|
|
28
|
+
/** The authored world named by a dedicated authoring chat. */
|
|
29
|
+
function authoredWorldOf(chatSessionId) {
|
|
30
|
+
if (!chatSessionId.startsWith(PREFIX)) return void 0;
|
|
31
|
+
try {
|
|
32
|
+
const id = decodeURIComponent(chatSessionId.slice(13));
|
|
33
|
+
return id === "" ? void 0 : id;
|
|
34
|
+
} catch {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region ../dsh-roleplay-model/src/trigger.ts
|
|
40
|
+
const COMPARISONS = [
|
|
41
|
+
"eq",
|
|
42
|
+
"ne",
|
|
43
|
+
"lt",
|
|
44
|
+
"le",
|
|
45
|
+
"gt",
|
|
46
|
+
"ge"
|
|
47
|
+
];
|
|
48
|
+
//#endregion
|
|
49
|
+
//#region ../dsh-roleplay-model/src/dice.ts
|
|
50
|
+
/** What a band of a check makes of an attempt; the same three results a round's outcome has. */
|
|
51
|
+
const DICE_RESULTS = [
|
|
52
|
+
"succeeded",
|
|
53
|
+
"partial",
|
|
54
|
+
"failed"
|
|
55
|
+
];
|
|
56
|
+
/** How a roll is read: by its total, or by how many of the dice came up high enough. */
|
|
57
|
+
const DICE_READINGS = ["total", "successes"];
|
|
58
|
+
/**
|
|
59
|
+
* What the value is compared with: `absolute` reads the value itself, `over` the amount by which it beats the target
|
|
60
|
+
* (a difficulty to meet or exceed), `under` the amount by which it stays below the target (a skill to roll under).
|
|
61
|
+
*/
|
|
62
|
+
const DICE_COMPARISONS = [
|
|
63
|
+
"absolute",
|
|
64
|
+
"over",
|
|
65
|
+
"under"
|
|
66
|
+
];
|
|
67
|
+
//#endregion
|
|
68
|
+
//#region src/host/import/card.ts
|
|
69
|
+
/** The file is not a character card this importer reads. The message says why, for the person who uploaded it. */
|
|
70
|
+
var ImportCardError = class extends Error {};
|
|
71
|
+
const PNG_SIGNATURE = Buffer.from([
|
|
72
|
+
137,
|
|
73
|
+
80,
|
|
74
|
+
78,
|
|
75
|
+
71,
|
|
76
|
+
13,
|
|
77
|
+
10,
|
|
78
|
+
26,
|
|
79
|
+
10
|
|
80
|
+
]);
|
|
81
|
+
const TEXT_CHUNKS = /* @__PURE__ */ new Set([
|
|
82
|
+
"tEXt",
|
|
83
|
+
"iTXt",
|
|
84
|
+
"zTXt"
|
|
85
|
+
]);
|
|
86
|
+
/** The keywords a card's data is stored under, the newer one first. */
|
|
87
|
+
const CARD_KEYWORDS = ["ccv3", "chara"];
|
|
88
|
+
function chunksOf(file) {
|
|
89
|
+
const chunks = [];
|
|
90
|
+
let at = PNG_SIGNATURE.length;
|
|
91
|
+
while (at + 12 <= file.length) {
|
|
92
|
+
const length = file.readUInt32BE(at);
|
|
93
|
+
const end = at + 12 + length;
|
|
94
|
+
if (end > file.length) throw new ImportCardError("the PNG file is damaged: a part of it is cut off");
|
|
95
|
+
chunks.push({
|
|
96
|
+
type: file.toString("latin1", at + 4, at + 8),
|
|
97
|
+
data: file.subarray(at + 8, at + 8 + length),
|
|
98
|
+
raw: file.subarray(at, end)
|
|
99
|
+
});
|
|
100
|
+
at = end;
|
|
101
|
+
}
|
|
102
|
+
return chunks;
|
|
103
|
+
}
|
|
104
|
+
/** The keyword and text of a PNG text chunk. */
|
|
105
|
+
function textOf(chunk) {
|
|
106
|
+
const end = chunk.data.indexOf(0);
|
|
107
|
+
if (end < 0) return void 0;
|
|
108
|
+
const keyword = chunk.data.toString("latin1", 0, end);
|
|
109
|
+
const rest = chunk.data.subarray(end + 1);
|
|
110
|
+
if (chunk.type === "tEXt") return {
|
|
111
|
+
keyword,
|
|
112
|
+
text: rest.toString("latin1")
|
|
113
|
+
};
|
|
114
|
+
if (chunk.type === "zTXt") return {
|
|
115
|
+
keyword,
|
|
116
|
+
text: inflateSync(rest.subarray(1)).toString("latin1")
|
|
117
|
+
};
|
|
118
|
+
const compressed = rest[0] === 1;
|
|
119
|
+
let from = 2;
|
|
120
|
+
for (let skipped = 0; skipped < 2; skipped += 1) from = rest.indexOf(0, from) + 1;
|
|
121
|
+
if (from <= 0) return void 0;
|
|
122
|
+
const body = rest.subarray(from);
|
|
123
|
+
return {
|
|
124
|
+
keyword,
|
|
125
|
+
text: (compressed ? inflateSync(body) : body).toString("utf8")
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/** The PNG without its text chunks: the picture, with none of the card's data in it. */
|
|
129
|
+
function pictureOf(file) {
|
|
130
|
+
return Buffer.concat([PNG_SIGNATURE, ...chunksOf(file).filter((chunk) => !TEXT_CHUNKS.has(chunk.type)).map((chunk) => chunk.raw)]);
|
|
131
|
+
}
|
|
132
|
+
function jsonOf(file, name) {
|
|
133
|
+
if (file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) {
|
|
134
|
+
const found = /* @__PURE__ */ new Map();
|
|
135
|
+
for (const chunk of chunksOf(file)) {
|
|
136
|
+
if (!TEXT_CHUNKS.has(chunk.type)) continue;
|
|
137
|
+
const text = textOf(chunk);
|
|
138
|
+
if (text !== void 0 && CARD_KEYWORDS.includes(text.keyword) && !found.has(text.keyword)) found.set(text.keyword, text.text);
|
|
139
|
+
}
|
|
140
|
+
const keyword = CARD_KEYWORDS.find((candidate) => found.has(candidate));
|
|
141
|
+
if (keyword === void 0) throw new ImportCardError(`${name} is a PNG picture with no character card in it`);
|
|
142
|
+
try {
|
|
143
|
+
return JSON.parse(Buffer.from(found.get(keyword).trim(), "base64").toString("utf8"));
|
|
144
|
+
} catch {
|
|
145
|
+
throw new ImportCardError(`the card data in ${name} is not readable`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
try {
|
|
149
|
+
return JSON.parse(file.toString("utf8").replace(/^/, ""));
|
|
150
|
+
} catch {
|
|
151
|
+
throw new ImportCardError(`${name} is neither a PNG picture with a card in it nor a JSON card`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const URL_PATTERN = /https?:\/\/[^\s"'`<>()[\]{}\\|^]+/gi;
|
|
155
|
+
/** Every web address in the strings of a document, at any depth; template placeholders and trailing punctuation are not part of one. */
|
|
156
|
+
function urlsOf(value) {
|
|
157
|
+
const found = /* @__PURE__ */ new Set();
|
|
158
|
+
const visit = (node, depth) => {
|
|
159
|
+
if (depth > 32) return;
|
|
160
|
+
if (typeof node === "string") for (const match of node.matchAll(URL_PATTERN)) {
|
|
161
|
+
const url = trimCharacters(match[0], ".,;:!?*_~", "end");
|
|
162
|
+
if (!url.includes("$") && url.length <= 2e3) found.add(url);
|
|
163
|
+
}
|
|
164
|
+
else if (Array.isArray(node)) for (const entry of node) visit(entry, depth + 1);
|
|
165
|
+
else if (typeof node === "object" && node !== null) for (const entry of Object.values(node)) visit(entry, depth + 1);
|
|
166
|
+
};
|
|
167
|
+
visit(value, 0);
|
|
168
|
+
return [...found];
|
|
169
|
+
}
|
|
170
|
+
const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
171
|
+
const text = (value) => typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
|
|
172
|
+
const texts = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" ? [entry] : typeof entry === "number" ? [String(entry)] : []) : [];
|
|
173
|
+
function entryOf(value, index) {
|
|
174
|
+
const entry = object(value);
|
|
175
|
+
if (entry === void 0) return void 0;
|
|
176
|
+
const position = entry["position"];
|
|
177
|
+
return {
|
|
178
|
+
id: `entry:${index}`,
|
|
179
|
+
title: text(entry["comment"]).trim() || text(entry["name"]).trim(),
|
|
180
|
+
keys: texts(entry["keys"]),
|
|
181
|
+
secondaryKeys: texts(entry["secondary_keys"]),
|
|
182
|
+
content: text(entry["content"]),
|
|
183
|
+
enabled: entry["enabled"] !== false,
|
|
184
|
+
constant: entry["constant"] === true,
|
|
185
|
+
selective: entry["selective"] === true,
|
|
186
|
+
position: typeof position === "string" ? position : typeof position === "number" ? String(position) : ""
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Reads a character card: a PNG with the card in its text chunk (the newer `ccv3` chunk when there is one), or the JSON of a card.
|
|
191
|
+
* Only V2 and V3 cards are read; a V2 card is carried over into the V3 shape, whose fields are a superset.
|
|
192
|
+
* @throws {ImportCardError} when the file is not such a card.
|
|
193
|
+
*/
|
|
194
|
+
function readCard(file, name) {
|
|
195
|
+
const root = object(jsonOf(file, name));
|
|
196
|
+
const spec = root === void 0 ? void 0 : root["spec"];
|
|
197
|
+
if (spec !== "chara_card_v2" && spec !== "chara_card_v3") throw new ImportCardError(spec === void 0 ? `${name} is not a V2 or V3 character card (it has no "spec")` : `${name} is a "${text(spec)}" card: only V2 and V3 cards are read`);
|
|
198
|
+
const data = object(root?.["data"]);
|
|
199
|
+
if (data === void 0) throw new ImportCardError(`${name} has no card data`);
|
|
200
|
+
const cardName = text(data["name"]).trim();
|
|
201
|
+
if (cardName === "") throw new ImportCardError(`${name} has a card with no name`);
|
|
202
|
+
const book = object(data["character_book"]);
|
|
203
|
+
const entries = Array.isArray(book?.["entries"]) ? book["entries"].flatMap((entry, index) => entryOf(entry, index) ?? []) : [];
|
|
204
|
+
const extensions = object(data["extensions"]) ?? {};
|
|
205
|
+
const scripts = [extensions["regex_scripts"], object(extensions["tavern_helper"])?.["scripts"]].reduce((count, list) => count + (Array.isArray(list) ? list.length : 0), 0);
|
|
206
|
+
return {
|
|
207
|
+
sourceSpec: spec,
|
|
208
|
+
name: cardName,
|
|
209
|
+
description: text(data["description"]),
|
|
210
|
+
personality: text(data["personality"]),
|
|
211
|
+
scenario: text(data["scenario"]),
|
|
212
|
+
firstMessage: text(data["first_mes"]),
|
|
213
|
+
alternateGreetings: texts(data["alternate_greetings"]),
|
|
214
|
+
messageExample: text(data["mes_example"]),
|
|
215
|
+
creatorNotes: text(data["creator_notes"]),
|
|
216
|
+
systemPrompt: text(data["system_prompt"]),
|
|
217
|
+
postHistoryInstructions: text(data["post_history_instructions"]),
|
|
218
|
+
tags: texts(data["tags"]),
|
|
219
|
+
creator: text(data["creator"]),
|
|
220
|
+
characterVersion: text(data["character_version"]),
|
|
221
|
+
...book === void 0 ? {} : { book: {
|
|
222
|
+
name: text(book["name"]),
|
|
223
|
+
description: text(book["description"]),
|
|
224
|
+
entries
|
|
225
|
+
} },
|
|
226
|
+
ignored: {
|
|
227
|
+
scripts,
|
|
228
|
+
extensions: Object.keys(extensions).filter((key) => ![
|
|
229
|
+
"talkativeness",
|
|
230
|
+
"fav",
|
|
231
|
+
"world",
|
|
232
|
+
"depth_prompt"
|
|
233
|
+
].includes(key))
|
|
234
|
+
},
|
|
235
|
+
urls: urlsOf(data)
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/** Whether a file looks like a PNG, so that its picture can be kept. */
|
|
239
|
+
const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE);
|
|
240
|
+
//#endregion
|
|
241
|
+
//#region src/host/import/output-ceiling.ts
|
|
242
|
+
/** A share of the model's context window, and the least and the fallback when the window is not known: the default of what one helper request may write. */
|
|
243
|
+
const AUTO_OUTPUT_SHARE = .1;
|
|
244
|
+
const AUTO_OUTPUT_MIN = 16e3;
|
|
245
|
+
const AUTO_OUTPUT_UNKNOWN = 32e3;
|
|
246
|
+
const windows = /* @__PURE__ */ new Map();
|
|
247
|
+
/** The most one request may write when the setting is automatic (0): a tenth of the window, at least 16 000 tokens. */
|
|
248
|
+
function autoOutputCeiling(window) {
|
|
249
|
+
return window === void 0 ? AUTO_OUTPUT_UNKNOWN : Math.max(AUTO_OUTPUT_MIN, Math.round(window * AUTO_OUTPUT_SHARE));
|
|
250
|
+
}
|
|
251
|
+
/** The ceiling for requests that cannot wait for the window to be looked up: what was learned from an earlier lookup of the model, or the fallback. */
|
|
252
|
+
function knownOutputCeiling(configured, model) {
|
|
253
|
+
if (configured > 0) return configured;
|
|
254
|
+
return autoOutputCeiling(model === void 0 ? void 0 : windows.get(`${model.provider}/${model.model}`));
|
|
255
|
+
}
|
|
256
|
+
/** The most one request of a helper may write: the setting when it names a number, else a share of the context window of the model the helper runs on (the chat's own unless one is named). */
|
|
257
|
+
async function outputCeiling(configured, agent, named, signal) {
|
|
258
|
+
if (configured > 0) return configured;
|
|
259
|
+
const config = agent.session.requestHeader()?.config;
|
|
260
|
+
const model = named ?? (config?.provider === void 0 || config.model === void 0 ? void 0 : {
|
|
261
|
+
provider: config.provider,
|
|
262
|
+
model: config.model
|
|
263
|
+
});
|
|
264
|
+
if (model === void 0) return autoOutputCeiling();
|
|
265
|
+
const key = `${model.provider}/${model.model}`;
|
|
266
|
+
let window = windows.get(key);
|
|
267
|
+
if (window === void 0) {
|
|
268
|
+
try {
|
|
269
|
+
window = (await agent.ctx.llm.resolveModelInfo(model.provider, model.model, signal)).context?.contextWindow;
|
|
270
|
+
} catch {
|
|
271
|
+
window = void 0;
|
|
272
|
+
}
|
|
273
|
+
if (window !== void 0) windows.set(key, window);
|
|
274
|
+
}
|
|
275
|
+
return autoOutputCeiling(window);
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/host/folders.ts
|
|
279
|
+
/**
|
|
280
|
+
* Names of the subfolders of `dir`, sorted. Symbolic links are not followed
|
|
281
|
+
* and a missing directory has none; any other failure is thrown.
|
|
282
|
+
*/
|
|
283
|
+
async function subfolders(dir) {
|
|
284
|
+
try {
|
|
285
|
+
return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (error.code === "ENOENT") return [];
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
//#endregion
|
|
292
|
+
//#region src/host/characters/load.ts
|
|
293
|
+
const CHARACTERS_DIR = "characters";
|
|
294
|
+
/**
|
|
295
|
+
* Read the cast of one world: every subfolder of `<world>/characters/` that
|
|
296
|
+
* holds a `character.json`. Ids must be unique; a repeated one is reported and
|
|
297
|
+
* the later character skipped.
|
|
298
|
+
*/
|
|
299
|
+
async function loadCharacters(worldDir) {
|
|
300
|
+
const dir = join(worldDir, CHARACTERS_DIR);
|
|
301
|
+
const result = {
|
|
302
|
+
characters: [],
|
|
303
|
+
problems: []
|
|
304
|
+
};
|
|
305
|
+
let folders;
|
|
306
|
+
try {
|
|
307
|
+
folders = await subfolders(dir);
|
|
308
|
+
} catch (error) {
|
|
309
|
+
result.problems.push({
|
|
310
|
+
path: dir,
|
|
311
|
+
message: errorMessage(error)
|
|
312
|
+
});
|
|
313
|
+
return result;
|
|
314
|
+
}
|
|
315
|
+
const folderById = /* @__PURE__ */ new Map();
|
|
316
|
+
for (const folder of folders) {
|
|
317
|
+
const file = join(dir, folder, CHARACTER_FILE_NAME);
|
|
318
|
+
try {
|
|
319
|
+
const character = await readDocument(file, (text) => parseCharacterFile(text, folder), result.problems);
|
|
320
|
+
if (character === void 0) continue;
|
|
321
|
+
const owner = folderById.get(character.id);
|
|
322
|
+
if (owner !== void 0) {
|
|
323
|
+
result.problems.push({
|
|
324
|
+
path: file,
|
|
325
|
+
message: `id "${character.id}" is already used by ${owner}`
|
|
326
|
+
});
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
folderById.set(character.id, folder);
|
|
330
|
+
result.characters.push(character);
|
|
331
|
+
} catch (error) {
|
|
332
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
333
|
+
path: file,
|
|
334
|
+
message: errorMessage(error)
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return result;
|
|
339
|
+
}
|
|
340
|
+
//#endregion
|
|
341
|
+
//#region src/host/calendar/load.ts
|
|
342
|
+
const CALENDAR_FILE_NAME = "calendar.json";
|
|
343
|
+
const HOLIDAY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,59}$/u;
|
|
344
|
+
/**
|
|
345
|
+
* Read `calendar.json`: the holidays of the world and the hemisphere its seasons follow (docs/world-format.md). A holiday is told by days (`12-25`,
|
|
346
|
+
* `09-21..09-22`, `nth:mon:1`, `season:winter`, a month, a weekday); it cannot name another holiday.
|
|
347
|
+
*/
|
|
348
|
+
function parseCalendarFile(text) {
|
|
349
|
+
const issues = [];
|
|
350
|
+
const reader = Reader.fromJson(text, issues);
|
|
351
|
+
if (reader === void 0) return {
|
|
352
|
+
ok: false,
|
|
353
|
+
issues
|
|
354
|
+
};
|
|
355
|
+
const hemisphere = reader.oneOf("hemisphere", ["north", "south"], "north");
|
|
356
|
+
const seen = /* @__PURE__ */ new Set();
|
|
357
|
+
const holidays = reader.objects("holidays").flatMap((entry) => {
|
|
358
|
+
const id = entry.string("id", { required: true });
|
|
359
|
+
const name = entry.string("name", { required: true });
|
|
360
|
+
const on = entry.strings("on");
|
|
361
|
+
if (id !== void 0 && !HOLIDAY_ID.test(id)) entry.fail("id", "is made of letters, digits, \"-\" and \"_\" (at most 60)");
|
|
362
|
+
if (id !== void 0 && seen.has(id)) entry.fail("id", `"${id}" is used by another holiday`);
|
|
363
|
+
if (id !== void 0) seen.add(id);
|
|
364
|
+
if (on.length === 0) entry.fail("on", `names no day: write days such as "12-25", "09-21..09-22", "nth:mon:1" or a month (${MONTH_NAMES.join(", ")}); seasons are ${SEASONS.join(", ")}`);
|
|
365
|
+
for (const problem of dayTokenProblems(on, "on")) entry.fail("on", problem.replace(/^on: /, ""));
|
|
366
|
+
return id === void 0 || name === void 0 ? [] : [{
|
|
367
|
+
id,
|
|
368
|
+
name,
|
|
369
|
+
on
|
|
370
|
+
}];
|
|
371
|
+
});
|
|
372
|
+
if (holidays.length > 60) reader.fail("holidays", `a world has at most 60 holidays`);
|
|
373
|
+
return issues.length > 0 ? {
|
|
374
|
+
ok: false,
|
|
375
|
+
issues
|
|
376
|
+
} : {
|
|
377
|
+
ok: true,
|
|
378
|
+
value: {
|
|
379
|
+
hemisphere,
|
|
380
|
+
holidays
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
/** The calendar of a world: an optional `<world>/calendar.json`; a world without one has none. */
|
|
385
|
+
async function loadCalendar(worldDir) {
|
|
386
|
+
const result = {
|
|
387
|
+
calendar: {
|
|
388
|
+
hemisphere: "north",
|
|
389
|
+
holidays: []
|
|
390
|
+
},
|
|
391
|
+
problems: []
|
|
392
|
+
};
|
|
393
|
+
const file = join(worldDir, CALENDAR_FILE_NAME);
|
|
394
|
+
try {
|
|
395
|
+
result.calendar = await readDocument(file, parseCalendarFile, result.problems) ?? result.calendar;
|
|
396
|
+
} catch (error) {
|
|
397
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
398
|
+
path: file,
|
|
399
|
+
message: errorMessage(error)
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return result;
|
|
403
|
+
}
|
|
404
|
+
//#endregion
|
|
405
|
+
//#region src/host/commands/load.ts
|
|
406
|
+
const COMMANDS_FILE_NAME = "commands.json";
|
|
407
|
+
/** The words the game itself uses after a slash. */
|
|
408
|
+
const RESERVED = /* @__PURE__ */ new Set(["ooc", "roll"]);
|
|
409
|
+
const WORD = /^[\p{L}\p{N}_]{1,30}$/u;
|
|
410
|
+
const KEY = /^[a-z][a-z0-9_]{0,29}$/;
|
|
411
|
+
const commandVariable = commandFlagKey;
|
|
412
|
+
/** The flag a command raises, as the world declares its variables. */
|
|
413
|
+
const commandFlag = (command) => ({
|
|
414
|
+
key: commandVariable(command),
|
|
415
|
+
name: `/${command.word}`,
|
|
416
|
+
kind: "flag",
|
|
417
|
+
subject: "world",
|
|
418
|
+
visibility: "hidden",
|
|
419
|
+
default: false,
|
|
420
|
+
description: command.description
|
|
421
|
+
});
|
|
422
|
+
/** Read `commands.json`: the slash commands a world defines (docs/world-format.md). */
|
|
423
|
+
function parseCommandsFile(text) {
|
|
424
|
+
const issues = [];
|
|
425
|
+
const reader = Reader.fromJson(text, issues);
|
|
426
|
+
if (reader === void 0) return {
|
|
427
|
+
ok: false,
|
|
428
|
+
issues
|
|
429
|
+
};
|
|
430
|
+
const commands = reader.objects("commands").flatMap((entry) => {
|
|
431
|
+
const word = entry.string("word", { required: true })?.trim().toLowerCase();
|
|
432
|
+
const description = entry.string("description", { required: true });
|
|
433
|
+
const given = entry.string("key");
|
|
434
|
+
if (word === void 0 || description === void 0) return [];
|
|
435
|
+
if (!WORD.test(word)) entry.fail("word", "must be letters, digits or underscores, at most 30");
|
|
436
|
+
if (RESERVED.has(word)) entry.fail("word", `"${word}" is used by the game itself`);
|
|
437
|
+
const key = given ?? (KEY.test(word) ? word : void 0);
|
|
438
|
+
if (key === void 0) entry.fail("key", "is required when the word is not plain lowercase ASCII: the name its flag is given (letters, digits, underscores)");
|
|
439
|
+
else if (!KEY.test(key)) entry.fail("key", "must be lowercase ASCII letters, digits and underscores, starting with a letter");
|
|
440
|
+
return key === void 0 ? [] : [{
|
|
441
|
+
word,
|
|
442
|
+
key,
|
|
443
|
+
description
|
|
444
|
+
}];
|
|
445
|
+
});
|
|
446
|
+
const seen = /* @__PURE__ */ new Set();
|
|
447
|
+
for (const command of commands) {
|
|
448
|
+
if (seen.has(command.word) || seen.has(`key:${command.key}`)) reader.fail("commands", `"${command.word}" is defined twice`);
|
|
449
|
+
seen.add(command.word);
|
|
450
|
+
seen.add(`key:${command.key}`);
|
|
451
|
+
}
|
|
452
|
+
if (commands.length > 20) reader.fail("commands", `a world has at most 20 commands`);
|
|
453
|
+
return issues.length > 0 ? {
|
|
454
|
+
ok: false,
|
|
455
|
+
issues
|
|
456
|
+
} : {
|
|
457
|
+
ok: true,
|
|
458
|
+
value: commands
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
/** The commands of a world: an optional `<world>/commands.json`. */
|
|
462
|
+
async function loadCommands(worldDir) {
|
|
463
|
+
const result = {
|
|
464
|
+
commands: [],
|
|
465
|
+
problems: []
|
|
466
|
+
};
|
|
467
|
+
const file = join(worldDir, COMMANDS_FILE_NAME);
|
|
468
|
+
try {
|
|
469
|
+
result.commands = await readDocument(file, parseCommandsFile, result.problems) ?? [];
|
|
470
|
+
} catch (error) {
|
|
471
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
472
|
+
path: file,
|
|
473
|
+
message: errorMessage(error)
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
return result;
|
|
477
|
+
}
|
|
478
|
+
//#endregion
|
|
479
|
+
//#region src/host/dice/load.ts
|
|
480
|
+
const DICE_FILE_NAME = "dice.json";
|
|
481
|
+
function readBand(band) {
|
|
482
|
+
const label = band.string("label", { required: true });
|
|
483
|
+
const result = band.oneOf("result", DICE_RESULTS, "failed");
|
|
484
|
+
const min = band.number("min");
|
|
485
|
+
const max = band.number("max");
|
|
486
|
+
const critical = band.raw("critical");
|
|
487
|
+
if (critical !== void 0 && critical !== null && typeof critical !== "boolean") band.fail("critical", "must be true or false");
|
|
488
|
+
if (band.raw("result") === void 0) band.fail("result", `is required: one of ${DICE_RESULTS.join(", ")}`);
|
|
489
|
+
return label === void 0 ? void 0 : {
|
|
490
|
+
label,
|
|
491
|
+
result,
|
|
492
|
+
...min === void 0 ? {} : { min },
|
|
493
|
+
...max === void 0 ? {} : { max },
|
|
494
|
+
...critical === true ? { critical: true } : {}
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* Read `dice.json`: the checks a world settles uncertain attempts with (docs/world-format.md). The dice and how their result is read are the world's:
|
|
499
|
+
* the game master rolls a check and is told the band the roll fell in, never a number to interpret.
|
|
500
|
+
*/
|
|
501
|
+
function parseDiceFile(text) {
|
|
502
|
+
const issues = [];
|
|
503
|
+
const reader = Reader.fromJson(text, issues);
|
|
504
|
+
if (reader === void 0) return {
|
|
505
|
+
ok: false,
|
|
506
|
+
issues
|
|
507
|
+
};
|
|
508
|
+
const checks = reader.objects("checks").flatMap((entry) => {
|
|
509
|
+
const key = entry.string("key", { required: true });
|
|
510
|
+
const name = entry.string("name", { required: true });
|
|
511
|
+
const use = entry.string("use", { required: true });
|
|
512
|
+
const dice = entry.string("dice", { required: true });
|
|
513
|
+
const reading = entry.oneOf("reading", DICE_READINGS, "total");
|
|
514
|
+
const compare = entry.oneOf("compare", DICE_COMPARISONS, "absolute");
|
|
515
|
+
const hit = entry.number("hit", { min: 1 });
|
|
516
|
+
const modifier = entry.string("modifier");
|
|
517
|
+
const bands = entry.objects("bands").flatMap((band) => {
|
|
518
|
+
const read = readBand(band);
|
|
519
|
+
return read === void 0 ? [] : [read];
|
|
520
|
+
});
|
|
521
|
+
if (key === void 0 || name === void 0 || use === void 0 || dice === void 0) return [];
|
|
522
|
+
const definition = {
|
|
523
|
+
key,
|
|
524
|
+
name,
|
|
525
|
+
use,
|
|
526
|
+
dice,
|
|
527
|
+
reading,
|
|
528
|
+
compare,
|
|
529
|
+
bands,
|
|
530
|
+
...hit === void 0 ? {} : { hit },
|
|
531
|
+
...modifier === void 0 || modifier === "" ? {} : { modifier }
|
|
532
|
+
};
|
|
533
|
+
for (const problem of checkProblems(definition)) entry.fail("", problem);
|
|
534
|
+
return [definition];
|
|
535
|
+
});
|
|
536
|
+
const seen = /* @__PURE__ */ new Set();
|
|
537
|
+
for (const check of checks) {
|
|
538
|
+
if (seen.has(check.key)) reader.fail("checks", `the key "${check.key}" is used by more than one check`);
|
|
539
|
+
seen.add(check.key);
|
|
540
|
+
}
|
|
541
|
+
if (checks.length > 40) reader.fail("checks", `a world has at most 40 checks`);
|
|
542
|
+
return issues.length > 0 ? {
|
|
543
|
+
ok: false,
|
|
544
|
+
issues
|
|
545
|
+
} : {
|
|
546
|
+
ok: true,
|
|
547
|
+
value: checks
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
/** The checks of a world: an optional `<world>/dice.json`; a world without one has none, and its game master rolls plain dice only. */
|
|
551
|
+
async function loadDice(worldDir) {
|
|
552
|
+
const result = {
|
|
553
|
+
checks: [],
|
|
554
|
+
problems: []
|
|
555
|
+
};
|
|
556
|
+
const file = join(worldDir, DICE_FILE_NAME);
|
|
557
|
+
try {
|
|
558
|
+
result.checks = await readDocument(file, parseDiceFile, result.problems) ?? [];
|
|
559
|
+
} catch (error) {
|
|
560
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
561
|
+
path: file,
|
|
562
|
+
message: errorMessage(error)
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
return result;
|
|
566
|
+
}
|
|
567
|
+
//#endregion
|
|
568
|
+
//#region src/host/factions/load.ts
|
|
569
|
+
const FACTIONS_DIR = "factions";
|
|
570
|
+
async function loadFactions(worldDir) {
|
|
571
|
+
const dir = join(worldDir, FACTIONS_DIR);
|
|
572
|
+
const result = {
|
|
573
|
+
factions: [],
|
|
574
|
+
problems: []
|
|
575
|
+
};
|
|
576
|
+
let folders;
|
|
577
|
+
try {
|
|
578
|
+
folders = await subfolders(dir);
|
|
579
|
+
} catch (error) {
|
|
580
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
581
|
+
path: dir,
|
|
582
|
+
message: errorMessage(error)
|
|
583
|
+
});
|
|
584
|
+
return result;
|
|
585
|
+
}
|
|
586
|
+
const owners = /* @__PURE__ */ new Map();
|
|
587
|
+
for (const folder of folders) {
|
|
588
|
+
const file = join(dir, folder, FACTION_FILE_NAME);
|
|
589
|
+
try {
|
|
590
|
+
const faction = await readDocument(file, (text) => parseFactionFile(text, folder), result.problems);
|
|
591
|
+
if (faction === void 0) continue;
|
|
592
|
+
const owner = owners.get(faction.id);
|
|
593
|
+
if (owner !== void 0) {
|
|
594
|
+
result.problems.push({
|
|
595
|
+
path: file,
|
|
596
|
+
message: `id "${faction.id}" is already used by ${owner}`
|
|
597
|
+
});
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
owners.set(faction.id, folder);
|
|
601
|
+
result.factions.push(faction);
|
|
602
|
+
} catch (error) {
|
|
603
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
604
|
+
path: file,
|
|
605
|
+
message: errorMessage(error)
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
if (result.factions.length > 100) result.problems.push({
|
|
610
|
+
path: dir,
|
|
611
|
+
message: `a world has at most 100 factions`
|
|
612
|
+
});
|
|
613
|
+
return result;
|
|
614
|
+
}
|
|
615
|
+
//#endregion
|
|
616
|
+
//#region src/host/items/load.ts
|
|
617
|
+
const ITEMS_DIR = "items";
|
|
618
|
+
/** At most this many items in one world. */
|
|
619
|
+
const MAX_ITEMS = 2e3;
|
|
620
|
+
/**
|
|
621
|
+
* Read the things of one world: every subfolder of `<world>/items/` that holds an `item.json`, and an
|
|
622
|
+
* optional `<world>/items/slots.json`. A world with no such folder has none. Ids must be unique; what
|
|
623
|
+
* a thing is worn in must be a slot, and where it starts, who owns it, what opens it and what it is
|
|
624
|
+
* inside must exist in the world, with no thing inside itself.
|
|
625
|
+
*/
|
|
626
|
+
async function loadItems(worldDir, context) {
|
|
627
|
+
const dir = join(worldDir, ITEMS_DIR);
|
|
628
|
+
const result = {
|
|
629
|
+
items: [],
|
|
630
|
+
slots: DEFAULT_SLOTS.map((slot) => ({ ...slot })),
|
|
631
|
+
problems: []
|
|
632
|
+
};
|
|
633
|
+
let folders;
|
|
634
|
+
try {
|
|
635
|
+
folders = await subfolders(dir);
|
|
636
|
+
} catch (error) {
|
|
637
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
638
|
+
path: dir,
|
|
639
|
+
message: errorMessage(error)
|
|
640
|
+
});
|
|
641
|
+
return result;
|
|
642
|
+
}
|
|
643
|
+
try {
|
|
644
|
+
const own = await readDocument(join(dir, SLOTS_FILE_NAME), parseSlotsFile, result.problems);
|
|
645
|
+
for (const slot of own ?? []) {
|
|
646
|
+
const at = result.slots.findIndex((existing) => existing.id === slot.id);
|
|
647
|
+
if (at < 0) result.slots.push(slot);
|
|
648
|
+
else result.slots[at] = slot;
|
|
649
|
+
}
|
|
650
|
+
} catch (error) {
|
|
651
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
652
|
+
path: join(dir, SLOTS_FILE_NAME),
|
|
653
|
+
message: errorMessage(error)
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
const folderOf = /* @__PURE__ */ new Map();
|
|
657
|
+
for (const folder of folders) {
|
|
658
|
+
const file = join(dir, folder, ITEM_FILE_NAME);
|
|
659
|
+
try {
|
|
660
|
+
const item = await readDocument(file, (text) => parseItemFile(text, folder), result.problems);
|
|
661
|
+
if (item === void 0) continue;
|
|
662
|
+
const owner = folderOf.get(item.id);
|
|
663
|
+
if (owner !== void 0) {
|
|
664
|
+
result.problems.push({
|
|
665
|
+
path: file,
|
|
666
|
+
message: `id "${item.id}" is already used by ${owner}`
|
|
667
|
+
});
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
folderOf.set(item.id, folder);
|
|
671
|
+
result.items.push(item);
|
|
672
|
+
} catch (error) {
|
|
673
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
674
|
+
path: file,
|
|
675
|
+
message: errorMessage(error)
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
if (result.items.length > 2e3) result.problems.push({
|
|
680
|
+
path: dir,
|
|
681
|
+
message: `a world has at most ${MAX_ITEMS} items`
|
|
682
|
+
});
|
|
683
|
+
const byId = new Map(result.items.map((item) => [item.id, item]));
|
|
684
|
+
const slotIds = new Set(result.slots.map((slot) => slot.id));
|
|
685
|
+
const places = new Map(context.locations.map((location) => [location.id, location]));
|
|
686
|
+
const characters = new Set(context.characters);
|
|
687
|
+
const fileOf = (id) => join(dir, folderOf.get(id) ?? id, ITEM_FILE_NAME);
|
|
688
|
+
for (const item of result.items) {
|
|
689
|
+
const problem = (message) => {
|
|
690
|
+
result.problems.push({
|
|
691
|
+
path: fileOf(item.id),
|
|
692
|
+
message
|
|
693
|
+
});
|
|
694
|
+
};
|
|
695
|
+
if (item.wearable !== void 0 && !slotIds.has(item.wearable)) problem(`wearable: "${item.wearable}" is not a slot (the slots are: ${[...slotIds].join(", ")}; add one in ${SLOTS_FILE_NAME})`);
|
|
696
|
+
if (item.owner !== void 0 && !characters.has(item.owner)) problem(`owner: "${item.owner}" is not a character of this world`);
|
|
697
|
+
for (const key of item.container?.openedBy ?? []) if (!byId.has(key)) problem(`container.opened_by: "${key}" is not an item of this world`);
|
|
698
|
+
const { start } = item;
|
|
699
|
+
if (start.kind === "location") {
|
|
700
|
+
const place = places.get(start.location);
|
|
701
|
+
if (place === void 0) problem(`location: "${start.location}" is not a place of this world`);
|
|
702
|
+
else if (start.feature !== void 0 && !place.features.some((feature) => feature.key === start.feature)) problem(`feature: ${place.name} has no feature "${start.feature}"`);
|
|
703
|
+
} else if (start.kind === "held" || start.kind === "worn") {
|
|
704
|
+
if (!characters.has(start.character)) problem(`${start.kind === "held" ? "held_by" : "worn_by"}: "${start.character}" is not a character of this world`);
|
|
705
|
+
} else if (start.kind === "inside") {
|
|
706
|
+
const box = byId.get(start.item);
|
|
707
|
+
if (box === void 0) problem(`inside: "${start.item}" is not an item of this world`);
|
|
708
|
+
else if (box.container === void 0) problem(`inside: ${box.name} is not a container`);
|
|
709
|
+
const seen = /* @__PURE__ */ new Set([item.id]);
|
|
710
|
+
for (let up = box; up !== void 0; up = up.start.kind === "inside" ? byId.get(up.start.item) : void 0) {
|
|
711
|
+
if (seen.has(up.id)) {
|
|
712
|
+
problem("inside: the items are inside each other in a circle");
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
seen.add(up.id);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
for (const place of context.locations) place.exits.forEach((exit, index) => {
|
|
720
|
+
for (const key of exit.openedBy ?? []) if (!byId.has(key)) result.problems.push({
|
|
721
|
+
path: join(worldDir, "locations", place.id, "location.json"),
|
|
722
|
+
message: `exits[${index}].opened_by: "${key}" is not an item of this world`
|
|
723
|
+
});
|
|
724
|
+
});
|
|
725
|
+
return result;
|
|
726
|
+
}
|
|
727
|
+
/** The items in an order where each comes after the container it starts in. */
|
|
728
|
+
function containersFirst(items) {
|
|
729
|
+
const ordered = [];
|
|
730
|
+
const placed = /* @__PURE__ */ new Set();
|
|
731
|
+
const byId = new Map(items.map((item) => [item.id, item]));
|
|
732
|
+
const place = (item) => {
|
|
733
|
+
if (placed.has(item.id)) return;
|
|
734
|
+
placed.add(item.id);
|
|
735
|
+
const box = item.start.kind === "inside" ? byId.get(item.start.item) : void 0;
|
|
736
|
+
if (box !== void 0) place(box);
|
|
737
|
+
ordered.push(item);
|
|
738
|
+
};
|
|
739
|
+
for (const item of items) place(item);
|
|
740
|
+
return ordered;
|
|
741
|
+
}
|
|
742
|
+
//#endregion
|
|
743
|
+
//#region src/host/locations/load.ts
|
|
744
|
+
const LOCATIONS_DIR = "locations";
|
|
745
|
+
/**
|
|
746
|
+
* Read the places of one world: every subfolder of `<world>/locations/` that holds a
|
|
747
|
+
* `location.json`. A world with no such folder has no places, which is fine. Ids must be unique;
|
|
748
|
+
* every parent and every exit must lead to a place of the world, and the places must not contain
|
|
749
|
+
* each other in a circle. Every problem is reported with the file it is in.
|
|
750
|
+
*/
|
|
751
|
+
async function loadLocations(worldDir) {
|
|
752
|
+
const dir = join(worldDir, LOCATIONS_DIR);
|
|
753
|
+
const result = {
|
|
754
|
+
locations: [],
|
|
755
|
+
problems: []
|
|
756
|
+
};
|
|
757
|
+
let folders;
|
|
758
|
+
try {
|
|
759
|
+
folders = await subfolders(dir);
|
|
760
|
+
} catch (error) {
|
|
761
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
762
|
+
path: dir,
|
|
763
|
+
message: errorMessage(error)
|
|
764
|
+
});
|
|
765
|
+
return result;
|
|
766
|
+
}
|
|
767
|
+
const files = /* @__PURE__ */ new Map();
|
|
768
|
+
for (const folder of folders) {
|
|
769
|
+
const file = join(dir, folder, LOCATION_FILE_NAME);
|
|
770
|
+
try {
|
|
771
|
+
const location = await readDocument(file, (text) => parseLocationFile(text, folder), result.problems);
|
|
772
|
+
if (location === void 0) continue;
|
|
773
|
+
const owner = files.get(location.id);
|
|
774
|
+
if (owner !== void 0) {
|
|
775
|
+
result.problems.push({
|
|
776
|
+
path: file,
|
|
777
|
+
message: `id "${location.id}" is already used by ${owner}`
|
|
778
|
+
});
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
files.set(location.id, folder);
|
|
782
|
+
result.locations.push(location);
|
|
783
|
+
} catch (error) {
|
|
784
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
785
|
+
path: file,
|
|
786
|
+
message: errorMessage(error)
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
if (result.locations.length > 500) result.problems.push({
|
|
791
|
+
path: dir,
|
|
792
|
+
message: `a world has at most 500 places`
|
|
793
|
+
});
|
|
794
|
+
const byId = new Map(result.locations.map((location) => [location.id, location]));
|
|
795
|
+
const fileOf = (id) => join(dir, files.get(id) ?? id, LOCATION_FILE_NAME);
|
|
796
|
+
for (const location of result.locations) {
|
|
797
|
+
if (location.parent !== void 0 && !byId.has(location.parent)) result.problems.push({
|
|
798
|
+
path: fileOf(location.id),
|
|
799
|
+
message: `parent: "${location.parent}" is not a place of this world`
|
|
800
|
+
});
|
|
801
|
+
if (location.parent === location.id) result.problems.push({
|
|
802
|
+
path: fileOf(location.id),
|
|
803
|
+
message: "parent: a place cannot be in itself"
|
|
804
|
+
});
|
|
805
|
+
location.exits.forEach((exit, index) => {
|
|
806
|
+
if (!byId.has(exit.to)) result.problems.push({
|
|
807
|
+
path: fileOf(location.id),
|
|
808
|
+
message: `exits[${index}].to: "${exit.to}" is not a place of this world`
|
|
809
|
+
});
|
|
810
|
+
if (exit.to === location.id) result.problems.push({
|
|
811
|
+
path: fileOf(location.id),
|
|
812
|
+
message: `exits[${index}].to: an exit must lead to another place`
|
|
813
|
+
});
|
|
814
|
+
});
|
|
815
|
+
const seen = /* @__PURE__ */ new Set();
|
|
816
|
+
for (let up = location.parent === location.id ? void 0 : location.parent; up !== void 0 && byId.has(up); up = byId.get(up)?.parent) {
|
|
817
|
+
if (up === location.id || seen.has(up)) {
|
|
818
|
+
result.problems.push({
|
|
819
|
+
path: fileOf(location.id),
|
|
820
|
+
message: "parent: the places contain each other in a circle"
|
|
821
|
+
});
|
|
822
|
+
break;
|
|
823
|
+
}
|
|
824
|
+
seen.add(up);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
return result;
|
|
828
|
+
}
|
|
829
|
+
/** The places in an order where each comes after the one it is in. */
|
|
830
|
+
function parentsFirst(locations) {
|
|
831
|
+
const ordered = [];
|
|
832
|
+
const placed = /* @__PURE__ */ new Set();
|
|
833
|
+
const byId = new Map(locations.map((location) => [location.id, location]));
|
|
834
|
+
const place = (location) => {
|
|
835
|
+
if (placed.has(location.id)) return;
|
|
836
|
+
placed.add(location.id);
|
|
837
|
+
const parent = location.parent === void 0 ? void 0 : byId.get(location.parent);
|
|
838
|
+
if (parent !== void 0) place(parent);
|
|
839
|
+
ordered.push(location);
|
|
840
|
+
};
|
|
841
|
+
for (const location of locations) place(location);
|
|
842
|
+
return ordered;
|
|
843
|
+
}
|
|
844
|
+
//#endregion
|
|
845
|
+
//#region src/host/lore/load.ts
|
|
846
|
+
const LORE_DIR = "lore";
|
|
847
|
+
async function loadLore(worldDir) {
|
|
848
|
+
const dir = join(worldDir, LORE_DIR);
|
|
849
|
+
const result = {
|
|
850
|
+
lore: [],
|
|
851
|
+
problems: []
|
|
852
|
+
};
|
|
853
|
+
let folders;
|
|
854
|
+
try {
|
|
855
|
+
folders = await subfolders(dir);
|
|
856
|
+
} catch (error) {
|
|
857
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
858
|
+
path: dir,
|
|
859
|
+
message: errorMessage(error)
|
|
860
|
+
});
|
|
861
|
+
return result;
|
|
862
|
+
}
|
|
863
|
+
const owners = /* @__PURE__ */ new Map();
|
|
864
|
+
for (const folder of folders) {
|
|
865
|
+
const file = join(dir, folder, LORE_FILE_NAME);
|
|
866
|
+
try {
|
|
867
|
+
const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
|
|
868
|
+
if (entry === void 0) continue;
|
|
869
|
+
const owner = owners.get(entry.id);
|
|
870
|
+
if (owner !== void 0) {
|
|
871
|
+
result.problems.push({
|
|
872
|
+
path: file,
|
|
873
|
+
message: `id "${entry.id}" is already used by ${owner}`
|
|
874
|
+
});
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
owners.set(entry.id, folder);
|
|
878
|
+
result.lore.push(entry);
|
|
879
|
+
} catch (error) {
|
|
880
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
881
|
+
path: file,
|
|
882
|
+
message: errorMessage(error)
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
if (result.lore.length > 500) result.problems.push({
|
|
887
|
+
path: dir,
|
|
888
|
+
message: `a world has at most 500 lore entries`
|
|
889
|
+
});
|
|
890
|
+
return result;
|
|
891
|
+
}
|
|
892
|
+
//#endregion
|
|
893
|
+
//#region src/host/triggers/load.ts
|
|
894
|
+
const TRIGGERS_FILE_NAME = "triggers.json";
|
|
895
|
+
/** Read `triggers.json`: a list of what the world does by itself when something comes true (docs/world-format.md). */
|
|
896
|
+
function parseTriggersFile(text) {
|
|
897
|
+
let data;
|
|
898
|
+
try {
|
|
899
|
+
data = JSON.parse(text.replace(/^/, ""));
|
|
900
|
+
} catch (error) {
|
|
901
|
+
return {
|
|
902
|
+
ok: false,
|
|
903
|
+
issues: [{
|
|
904
|
+
path: "",
|
|
905
|
+
message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
906
|
+
}]
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
if (!Array.isArray(data)) return {
|
|
910
|
+
ok: false,
|
|
911
|
+
issues: [{
|
|
912
|
+
path: "",
|
|
913
|
+
message: "expected a list of triggers"
|
|
914
|
+
}]
|
|
915
|
+
};
|
|
916
|
+
const issues = [];
|
|
917
|
+
const definitions = [];
|
|
918
|
+
data.forEach((entry, index) => {
|
|
919
|
+
const parsed = readTriggerDefinition(entry, `[${index}]`);
|
|
920
|
+
if ("problems" in parsed) for (const problem of parsed.problems) {
|
|
921
|
+
const split = problem.indexOf(": ");
|
|
922
|
+
issues.push({
|
|
923
|
+
path: split < 0 ? `[${index}]` : problem.slice(0, split),
|
|
924
|
+
message: split < 0 ? problem : problem.slice(split + 2)
|
|
925
|
+
});
|
|
926
|
+
}
|
|
927
|
+
else definitions.push(parsed.definition);
|
|
928
|
+
});
|
|
929
|
+
const keys = definitions.map((definition) => definition.key);
|
|
930
|
+
keys.forEach((key, index) => {
|
|
931
|
+
if (keys.indexOf(key) !== index) issues.push({
|
|
932
|
+
path: "",
|
|
933
|
+
message: `the trigger "${key}" is defined twice`
|
|
934
|
+
});
|
|
935
|
+
});
|
|
936
|
+
return issues.length > 0 ? {
|
|
937
|
+
ok: false,
|
|
938
|
+
issues
|
|
939
|
+
} : {
|
|
940
|
+
ok: true,
|
|
941
|
+
value: definitions
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
/** Read the world's triggers: an optional `<world>/triggers.json`. A world with none only has what the story makes. */
|
|
945
|
+
async function loadTriggers(worldDir) {
|
|
946
|
+
const result = {
|
|
947
|
+
triggers: [],
|
|
948
|
+
problems: []
|
|
949
|
+
};
|
|
950
|
+
const file = join(worldDir, TRIGGERS_FILE_NAME);
|
|
951
|
+
try {
|
|
952
|
+
result.triggers = await readDocument(file, parseTriggersFile, result.problems) ?? [];
|
|
953
|
+
} catch (error) {
|
|
954
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
955
|
+
path: file,
|
|
956
|
+
message: errorMessage(error)
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
return result;
|
|
960
|
+
}
|
|
961
|
+
//#endregion
|
|
962
|
+
//#region src/host/sessions/populate.ts
|
|
963
|
+
/** What is wrong with how the characters stand towards each other, found before anything is created. */
|
|
964
|
+
function relationshipProblems(characters) {
|
|
965
|
+
const ids = new Set(characters.map((character) => character.id));
|
|
966
|
+
return characters.flatMap((character) => (character.relationships ?? []).flatMap((relation) => {
|
|
967
|
+
if (relation.to === character.id) return [`${character.id}: relationships: a character has no relationship with itself`];
|
|
968
|
+
return ids.has(relation.to) ? [] : [`${character.id}: relationships: "${relation.to}" is not a character of this world`];
|
|
969
|
+
}));
|
|
970
|
+
}
|
|
971
|
+
function factionProblems(factions, characters) {
|
|
972
|
+
const factionIds = new Set(factions.map((faction) => faction.id));
|
|
973
|
+
const characterIds = new Set(characters.map((character) => character.id));
|
|
974
|
+
return factions.flatMap((faction) => [...faction.members.flatMap((member) => characterIds.has(member.character) ? [] : [`${faction.id}: members: "${member.character}" is not a character of this world`]), ...faction.relationships.flatMap((relation) => {
|
|
975
|
+
if (relation.to.kind === "faction" && relation.to.id === faction.id) return [`${faction.id}: relationships: a faction has no relationship with itself`];
|
|
976
|
+
return (relation.to.kind === "character" ? characterIds : factionIds).has(relation.to.id) ? [] : [`${faction.id}: relationships: "${relation.to.id}" is not a ${relation.to.kind} of this world`];
|
|
977
|
+
})]);
|
|
978
|
+
}
|
|
979
|
+
/** What is wrong with the places, things and directed ways characters are authored to know. */
|
|
980
|
+
function knowledgeProblems(characters, locations, items, lore = []) {
|
|
981
|
+
const places = new Map(locations.map((location) => [location.id, location]));
|
|
982
|
+
const things = new Set(items.map((item) => item.id));
|
|
983
|
+
const loreIds = new Set(lore.map((entry) => entry.id));
|
|
984
|
+
const wayExists = (from, to) => places.get(from)?.exits.some((exit) => exit.to === to) === true || places.get(to)?.exits.some((exit) => exit.to === from && !exit.oneWay) === true;
|
|
985
|
+
return characters.flatMap((character) => {
|
|
986
|
+
const prefix = `${character.id}: knowledge`;
|
|
987
|
+
const knowledge = character.knowledge;
|
|
988
|
+
if (knowledge === void 0) return [];
|
|
989
|
+
return [
|
|
990
|
+
...knowledge.locations.flatMap((key) => places.has(key) ? [] : [`${prefix}.locations: "${key}" is not a place of this world`]),
|
|
991
|
+
...knowledge.items.flatMap((key) => things.has(key) ? [] : [`${prefix}.items: "${key}" is not an item of this world`]),
|
|
992
|
+
...knowledge.exits.flatMap(({ from, to }) => wayExists(from, to) ? [] : [`${prefix}.exits: there is no exit from "${from}" to "${to}"`]),
|
|
993
|
+
...(knowledge.lore ?? []).flatMap((key) => loreIds.has(key) ? [] : [`${prefix}.lore: "${key}" is not lore of this world`])
|
|
994
|
+
];
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
/** Whether a world's characters include the one a lore entry names by id, name or alias. */
|
|
998
|
+
function knowsCharacter(characters, reference) {
|
|
999
|
+
const key = reference.normalize("NFKC").toLowerCase();
|
|
1000
|
+
return characters.some((character) => character.id === reference || [character.name, ...character.aliases].some((name) => name.normalize("NFKC").toLowerCase() === key));
|
|
1001
|
+
}
|
|
1002
|
+
function loreProblems(lore, world) {
|
|
1003
|
+
const ids = {
|
|
1004
|
+
character: new Set(world.characters.map((x) => x.id)),
|
|
1005
|
+
faction: new Set(world.factions.map((x) => x.id)),
|
|
1006
|
+
location: new Set(world.locations.map((x) => x.id)),
|
|
1007
|
+
item: new Set(world.items.map((x) => x.id)),
|
|
1008
|
+
lore: new Set(lore.map((x) => x.id))
|
|
1009
|
+
};
|
|
1010
|
+
return lore.flatMap((entry) => [
|
|
1011
|
+
...entry.subjects.flatMap((subject) => ids[subject.kind].has(subject.id) ? [] : [`${entry.id}: subjects: "${subject.id}" is not a ${subject.kind} of this world`]),
|
|
1012
|
+
...entry.knownBy.flatMap((reference) => knowsCharacter(world.characters, reference) ? [] : [`${entry.id}: known_by: "${reference}" is not a character of this world`]),
|
|
1013
|
+
...entry.related.flatMap((id) => id === entry.id ? [`${entry.id}: related: lore cannot relate to itself`] : ids.lore.has(id) ? [] : [`${entry.id}: related: "${id}" is not lore of this world`])
|
|
1014
|
+
]);
|
|
1015
|
+
}
|
|
1016
|
+
/** `turn` is when the characters that know an entry learned it: 0 at the start, the story's turn when a lorebook is added later. */
|
|
1017
|
+
function populateLore(session, definitions, turn = 0) {
|
|
1018
|
+
for (const entry of definitions) session.lore.add({
|
|
1019
|
+
sourceId: entry.id,
|
|
1020
|
+
title: entry.title,
|
|
1021
|
+
kind: entry.kind,
|
|
1022
|
+
scope: entry.scope,
|
|
1023
|
+
summary: entry.summary,
|
|
1024
|
+
body: entry.body,
|
|
1025
|
+
...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
|
|
1026
|
+
...entry.endsAt === void 0 ? {} : { endsAt: entry.endsAt },
|
|
1027
|
+
subjects: [],
|
|
1028
|
+
related: [],
|
|
1029
|
+
sources: entry.sources
|
|
1030
|
+
});
|
|
1031
|
+
const subject = (wanted) => ({
|
|
1032
|
+
kind: wanted.kind,
|
|
1033
|
+
id: wanted.kind === "character" ? session.characters.getBySourceId(wanted.id).id : wanted.kind === "faction" ? session.factions.getBySourceId(wanted.id).id : wanted.kind === "location" ? session.locations.getBySourceId(wanted.id).id : wanted.kind === "item" ? session.items.getBySourceId(wanted.id).id : session.lore.getBySourceId(wanted.id).id
|
|
1034
|
+
});
|
|
1035
|
+
for (const entry of definitions) session.lore.update(session.lore.getBySourceId(entry.id).id, {
|
|
1036
|
+
subjects: entry.subjects.map(subject),
|
|
1037
|
+
related: entry.related.map((id) => session.lore.getBySourceId(id).id)
|
|
1038
|
+
});
|
|
1039
|
+
for (const entry of definitions) {
|
|
1040
|
+
const lore = session.lore.getBySourceId(entry.id);
|
|
1041
|
+
for (const reference of entry.knownBy) {
|
|
1042
|
+
const knower = session.characters.getBySourceId(reference) ?? session.characters.findByName(reference)[0];
|
|
1043
|
+
if (knower !== void 0) session.knowledge.learn(knower.id, "lore", lore.id, turn);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
/** What is wrong with where the characters start, found before anything is created. */
|
|
1048
|
+
function startingPlaceProblems(characters, locations) {
|
|
1049
|
+
const byId = new Map(locations.map((location) => [location.id, location]));
|
|
1050
|
+
return characters.flatMap((character) => {
|
|
1051
|
+
const place = character.start.place;
|
|
1052
|
+
if (place === void 0) return [];
|
|
1053
|
+
const location = byId.get(place.location);
|
|
1054
|
+
if (location === void 0) return [`${character.id}: start.location "${place.location}" is not a place of this world`];
|
|
1055
|
+
if (place.feature !== void 0 && !location.features.some((feature) => feature.key === place.feature)) return [`${character.id}: start.feature "${place.feature}" is not a feature of ${location.name} (it has: ${location.features.map((feature) => feature.key).join(", ") || "none"})`];
|
|
1056
|
+
return [];
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
/** Declare what the world tracks and give everything the values it starts with. */
|
|
1060
|
+
function populateVariables(session, defs, world) {
|
|
1061
|
+
for (const def of defs) session.variables.define(def);
|
|
1062
|
+
const give = (kind, id, values) => {
|
|
1063
|
+
for (const [key, value] of Object.entries(values ?? {})) session.variables.set(key, kind, id, { value }, 0);
|
|
1064
|
+
};
|
|
1065
|
+
for (const entry of world.characters) give("character", session.characters.getBySourceId(entry.id).id, entry.variables);
|
|
1066
|
+
for (const entry of world.items) give("item", session.items.getBySourceId(entry.id).id, entry.variables);
|
|
1067
|
+
for (const entry of world.locations) give("location", session.locations.getBySourceId(entry.id).id, entry.variables);
|
|
1068
|
+
give("world", 0, world.values);
|
|
1069
|
+
}
|
|
1070
|
+
/** What is wrong with the days characters are given, found before anything is created: places that are not in the world. */
|
|
1071
|
+
function routineProblems(characters, locations, calendar) {
|
|
1072
|
+
calendar ??= {
|
|
1073
|
+
hemisphere: "north",
|
|
1074
|
+
holidays: []
|
|
1075
|
+
};
|
|
1076
|
+
const byId = new Map(locations.map((location) => [location.id, location]));
|
|
1077
|
+
const holidays = new Set(calendar.holidays.map((holiday) => holiday.id));
|
|
1078
|
+
return characters.flatMap((character) => (character.routine ?? []).flatMap((window, index) => {
|
|
1079
|
+
const days = dayTokenProblems(window.on ?? [], `${character.id}: routine[${index}].on`, holidays);
|
|
1080
|
+
if (days.length > 0) return days;
|
|
1081
|
+
if (window.location === void 0) return [];
|
|
1082
|
+
const location = byId.get(window.location);
|
|
1083
|
+
if (location === void 0) return [`${character.id}: routine[${index}].location "${window.location}" is not a place of this world`];
|
|
1084
|
+
if (window.feature !== void 0 && !location.features.some((feature) => feature.key === window.feature)) return [`${character.id}: routine[${index}].feature "${window.feature}" is not a feature of ${location.name}`];
|
|
1085
|
+
return [];
|
|
1086
|
+
}));
|
|
1087
|
+
}
|
|
1088
|
+
/** Keeps the checks of the world with the story: what its game master rolls and how the dice are read. */
|
|
1089
|
+
function populateDice(session, checks) {
|
|
1090
|
+
for (const check of checks) session.dice.define(check);
|
|
1091
|
+
}
|
|
1092
|
+
/** Keeps the world's calendar with the story, for the days a routine or a trigger waits for. */
|
|
1093
|
+
function populateCalendar(session, calendar) {
|
|
1094
|
+
if (calendar.holidays.length > 0 || calendar.hemisphere !== "north") writeCalendar(session.metadata, calendar);
|
|
1095
|
+
}
|
|
1096
|
+
/** Gives each character its recurring day, with the places by their ids in the world. */
|
|
1097
|
+
function populateRoutines(session, characters) {
|
|
1098
|
+
for (const { id, routine } of characters) {
|
|
1099
|
+
if (routine === void 0 || routine.length === 0) continue;
|
|
1100
|
+
session.routines.replace(session.characters.getBySourceId(id).id, routine.map((window) => ({
|
|
1101
|
+
days: window.days.map((day) => WEEKDAY_NAMES.indexOf(day)),
|
|
1102
|
+
on: window.on ?? [],
|
|
1103
|
+
start: parseTimeOfDay(window.from),
|
|
1104
|
+
end: parseTimeOfDay(window.to),
|
|
1105
|
+
activity: window.activity,
|
|
1106
|
+
interruptible: window.interruptible,
|
|
1107
|
+
...window.location === void 0 ? {} : { locationId: session.locations.getBySourceId(window.location).id },
|
|
1108
|
+
...window.feature === void 0 ? {} : { featureKey: window.feature },
|
|
1109
|
+
...window.position === void 0 ? {} : { position: window.position }
|
|
1110
|
+
})));
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
/** Put a world's places into a new session: each inside the one it belongs to, with the ways between them (both ways unless the file says one way). */
|
|
1114
|
+
function populateLocations(session, locations) {
|
|
1115
|
+
const ordered = parentsFirst(locations);
|
|
1116
|
+
for (const { id, name, description, parent, features, visualIdentity } of ordered) {
|
|
1117
|
+
const parentId = parent === void 0 ? void 0 : session.locations.getBySourceId(parent)?.id;
|
|
1118
|
+
const stored = session.locations.add({
|
|
1119
|
+
sourceId: id,
|
|
1120
|
+
name,
|
|
1121
|
+
description,
|
|
1122
|
+
features,
|
|
1123
|
+
...parentId === void 0 ? {} : { parentId }
|
|
1124
|
+
});
|
|
1125
|
+
if (visualIdentity !== void 0) session.visualIdentities.set("location", stored.id, visualIdentity);
|
|
1126
|
+
}
|
|
1127
|
+
for (const location of ordered) {
|
|
1128
|
+
const from = session.locations.getBySourceId(location.id);
|
|
1129
|
+
for (const exit of location.exits) {
|
|
1130
|
+
const to = session.locations.getBySourceId(exit.to);
|
|
1131
|
+
const shared = {
|
|
1132
|
+
...exit.travelSeconds === void 0 ? {} : { travelSeconds: exit.travelSeconds },
|
|
1133
|
+
state: exit.state,
|
|
1134
|
+
note: exit.note
|
|
1135
|
+
};
|
|
1136
|
+
if (session.locations.getExit(from.id, to.id) === void 0) session.locations.addExit({
|
|
1137
|
+
fromId: from.id,
|
|
1138
|
+
toId: to.id,
|
|
1139
|
+
description: exit.description,
|
|
1140
|
+
...shared
|
|
1141
|
+
});
|
|
1142
|
+
if (!exit.oneWay && session.locations.getExit(to.id, from.id) === void 0) session.locations.addExit({
|
|
1143
|
+
fromId: to.id,
|
|
1144
|
+
toId: from.id,
|
|
1145
|
+
description: exit.backDescription ?? exit.description,
|
|
1146
|
+
...shared
|
|
1147
|
+
});
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Put a world's cast into a new session: each character with the state it
|
|
1153
|
+
* starts in and its intents. The player controls the character whose world id
|
|
1154
|
+
* is `playerId`; the agent controls everyone else.
|
|
1155
|
+
*/
|
|
1156
|
+
function populateCharacters(session, characters, playerId) {
|
|
1157
|
+
for (const { id, start, relationships: _relationships, knowledge: _knowledge, routine: _routine, visualIdentity, ...identity } of characters) {
|
|
1158
|
+
const character = session.characters.add({
|
|
1159
|
+
...identity,
|
|
1160
|
+
sourceId: id,
|
|
1161
|
+
control: id === playerId ? "player" : "agent"
|
|
1162
|
+
});
|
|
1163
|
+
if (visualIdentity !== void 0) session.visualIdentities.set("character", character.id, visualIdentity);
|
|
1164
|
+
const { intents, place, emotion, ...state } = start;
|
|
1165
|
+
session.characterStates.create(character.id, state);
|
|
1166
|
+
if (emotion !== void 0) for (const axis of [
|
|
1167
|
+
"valence",
|
|
1168
|
+
"arousal",
|
|
1169
|
+
"dominance"
|
|
1170
|
+
]) session.variables.set(axis, "character", character.id, {
|
|
1171
|
+
value: emotion.immediate[axis],
|
|
1172
|
+
baseline: emotion.baseline[axis]
|
|
1173
|
+
}, 0);
|
|
1174
|
+
for (const intent of intents) session.intents.add(character.id, intent);
|
|
1175
|
+
if (place !== void 0) {
|
|
1176
|
+
const location = session.locations.getBySourceId(place.location);
|
|
1177
|
+
session.placements.place("character", character.id, {
|
|
1178
|
+
locationId: location.id,
|
|
1179
|
+
...place.position === void 0 ? {} : { position: place.position },
|
|
1180
|
+
...place.feature === void 0 ? {} : { featureKey: place.feature }
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
for (const { id, relationships } of characters) {
|
|
1185
|
+
const from = session.characters.getBySourceId(id);
|
|
1186
|
+
for (const relation of relationships ?? []) session.relationships.upsert(from.id, session.characters.getBySourceId(relation.to).id, {
|
|
1187
|
+
label: relation.label,
|
|
1188
|
+
summary: relation.summary,
|
|
1189
|
+
familiarity: relation.familiarity,
|
|
1190
|
+
trust: relation.trust,
|
|
1191
|
+
affinity: relation.affinity,
|
|
1192
|
+
tension: relation.tension
|
|
1193
|
+
}, 0);
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
function populateFactions(session, factions) {
|
|
1197
|
+
for (const definition of factions) {
|
|
1198
|
+
const faction = session.factions.add({
|
|
1199
|
+
sourceId: definition.id,
|
|
1200
|
+
name: definition.name,
|
|
1201
|
+
aliases: definition.aliases,
|
|
1202
|
+
summary: definition.summary,
|
|
1203
|
+
description: definition.description,
|
|
1204
|
+
values: definition.values,
|
|
1205
|
+
structure: definition.structure
|
|
1206
|
+
});
|
|
1207
|
+
session.factionStates.create(faction.id, definition.start);
|
|
1208
|
+
for (const goal of definition.start.goals) session.factionIntents.add(faction.id, goal);
|
|
1209
|
+
}
|
|
1210
|
+
for (const definition of factions) {
|
|
1211
|
+
const faction = session.factions.getBySourceId(definition.id);
|
|
1212
|
+
for (const member of definition.members) {
|
|
1213
|
+
const character = session.characters.getBySourceId(member.character);
|
|
1214
|
+
session.factionMemberships.upsert(faction.id, character.id, member, 0);
|
|
1215
|
+
if (session.factionRelationships.get("character", character.id, "faction", faction.id) === void 0) session.factionRelationships.upsert("character", character.id, "faction", faction.id, {
|
|
1216
|
+
label: member.role || "member",
|
|
1217
|
+
familiarity: 1
|
|
1218
|
+
}, 0);
|
|
1219
|
+
}
|
|
1220
|
+
for (const relation of definition.relationships) {
|
|
1221
|
+
const target = relation.to.kind === "character" ? session.characters.getBySourceId(relation.to.id) : session.factions.getBySourceId(relation.to.id);
|
|
1222
|
+
session.factionRelationships.upsert("faction", faction.id, relation.to.kind, target.id, relation, 0);
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
/** Give each character its authored knowledge, plus what is visible where it starts. */
|
|
1227
|
+
function populateKnowledge(session, characters) {
|
|
1228
|
+
for (const definition of characters) {
|
|
1229
|
+
const character = session.characters.getBySourceId(definition.id);
|
|
1230
|
+
for (const key of definition.knowledge?.locations ?? []) session.knowledge.learn(character.id, "location", session.locations.getBySourceId(key).id, 0);
|
|
1231
|
+
for (const key of definition.knowledge?.items ?? []) session.knowledge.learn(character.id, "item", session.items.getBySourceId(key).id, 0);
|
|
1232
|
+
for (const wanted of definition.knowledge?.exits ?? []) {
|
|
1233
|
+
const exit = session.locations.getExit(session.locations.getBySourceId(wanted.from).id, session.locations.getBySourceId(wanted.to).id);
|
|
1234
|
+
session.knowledge.learn(character.id, "exit", exit.id, 0);
|
|
1235
|
+
session.knowledge.learn(character.id, "location", exit.fromId, 0);
|
|
1236
|
+
session.knowledge.learn(character.id, "location", exit.toId, 0);
|
|
1237
|
+
}
|
|
1238
|
+
for (const key of definition.knowledge?.lore ?? []) session.knowledge.learn(character.id, "lore", session.lore.getBySourceId(key).id, 0);
|
|
1239
|
+
const placement = session.placements.get("character", character.id);
|
|
1240
|
+
if (placement === void 0) continue;
|
|
1241
|
+
session.knowledge.learn(character.id, "location", placement.locationId, 0, true);
|
|
1242
|
+
for (const exit of session.locations.exitsFrom(placement.locationId)) {
|
|
1243
|
+
session.knowledge.learn(character.id, "exit", exit.id, 0, true);
|
|
1244
|
+
session.knowledge.learn(character.id, "location", exit.toId, 0);
|
|
1245
|
+
}
|
|
1246
|
+
for (const { item } of session.items.contents({
|
|
1247
|
+
kind: "location",
|
|
1248
|
+
id: placement.locationId
|
|
1249
|
+
})) if (!item.hidden) session.knowledge.learn(character.id, "item", item.id, 0, true);
|
|
1250
|
+
for (const { item } of session.items.contents({
|
|
1251
|
+
kind: "character",
|
|
1252
|
+
id: character.id
|
|
1253
|
+
})) session.knowledge.learn(character.id, "item", item.id, 0, true);
|
|
1254
|
+
for (const other of session.placements.at(placement.locationId, "character")) if (other.entityId !== character.id && session.relationships.get(character.id, other.entityId) === void 0) session.relationships.upsert(character.id, other.entityId, { label: "acquaintance" }, 0);
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Put a world's slots and things into a new session, each where it starts, with what opens each lock. Containers come
|
|
1259
|
+
* before what is in them; what opens an exit is set for both directions of it.
|
|
1260
|
+
*/
|
|
1261
|
+
function populateItems(session, items, slots, locations) {
|
|
1262
|
+
for (const slot of slots) session.slots.upsert(slot);
|
|
1263
|
+
const made = /* @__PURE__ */ new Map();
|
|
1264
|
+
for (const definition of containersFirst(items)) {
|
|
1265
|
+
const { start } = definition;
|
|
1266
|
+
const holder = start.kind === "location" ? {
|
|
1267
|
+
kind: "location",
|
|
1268
|
+
locationId: session.locations.getBySourceId(start.location).id,
|
|
1269
|
+
...start.position === void 0 ? {} : { position: start.position },
|
|
1270
|
+
...start.feature === void 0 ? {} : { featureKey: start.feature }
|
|
1271
|
+
} : start.kind === "held" ? {
|
|
1272
|
+
kind: "character",
|
|
1273
|
+
characterId: session.characters.getBySourceId(start.character).id,
|
|
1274
|
+
mode: "held"
|
|
1275
|
+
} : start.kind === "worn" ? {
|
|
1276
|
+
kind: "character",
|
|
1277
|
+
characterId: session.characters.getBySourceId(start.character).id,
|
|
1278
|
+
mode: "worn",
|
|
1279
|
+
slot: definition.wearable,
|
|
1280
|
+
...start.position === void 0 ? {} : { position: start.position }
|
|
1281
|
+
} : {
|
|
1282
|
+
kind: "item",
|
|
1283
|
+
itemId: made.get(start.item),
|
|
1284
|
+
...start.position === void 0 ? {} : { position: start.position }
|
|
1285
|
+
};
|
|
1286
|
+
const item = session.items.add({
|
|
1287
|
+
sourceId: definition.id,
|
|
1288
|
+
name: definition.name,
|
|
1289
|
+
description: definition.description,
|
|
1290
|
+
quantity: definition.quantity,
|
|
1291
|
+
unique: definition.unique,
|
|
1292
|
+
quality: definition.quality,
|
|
1293
|
+
notable: definition.notable,
|
|
1294
|
+
hidden: definition.hidden,
|
|
1295
|
+
...definition.wearable === void 0 ? {} : { wearableSlot: definition.wearable },
|
|
1296
|
+
...definition.container === void 0 ? {} : { container: { state: definition.container.state } },
|
|
1297
|
+
...definition.owner === void 0 ? {} : { ownerId: session.characters.getBySourceId(definition.owner).id }
|
|
1298
|
+
}, holder);
|
|
1299
|
+
if (definition.visualIdentity !== void 0) session.visualIdentities.set("item", item.id, definition.visualIdentity);
|
|
1300
|
+
made.set(definition.id, item.id);
|
|
1301
|
+
}
|
|
1302
|
+
for (const definition of items) if (definition.container !== void 0 && definition.container.openedBy.length > 0) session.items.setOpeners({
|
|
1303
|
+
kind: "item",
|
|
1304
|
+
id: made.get(definition.id)
|
|
1305
|
+
}, definition.container.openedBy.map((key) => made.get(key)));
|
|
1306
|
+
for (const place of locations) {
|
|
1307
|
+
const from = session.locations.getBySourceId(place.id);
|
|
1308
|
+
for (const exit of place.exits) {
|
|
1309
|
+
if ((exit.openedBy ?? []).length === 0) continue;
|
|
1310
|
+
const to = session.locations.getBySourceId(exit.to);
|
|
1311
|
+
for (const [a, b] of [[from.id, to.id], [to.id, from.id]]) {
|
|
1312
|
+
const way = session.locations.getExit(a, b);
|
|
1313
|
+
if (way !== void 0) session.items.setOpeners({
|
|
1314
|
+
kind: "exit",
|
|
1315
|
+
id: way.id
|
|
1316
|
+
}, exit.openedBy.map((key) => made.get(key)));
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
/** Starts the story's clock: at the wall clock when it follows it, and otherwise at the world's starting time (or now, when the world has none). */
|
|
1322
|
+
function populateClock(session, settings, world, wall) {
|
|
1323
|
+
const start = settings.mode === "real" ? wall : world?.startingTime ?? Math.floor(wall / MINUTE) * MINUTE;
|
|
1324
|
+
session.clock.start(settings.mode, start);
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* Make the world's triggers, once everything they can name exists.
|
|
1328
|
+
* @throws {Error} naming each trigger that names something the world does not have.
|
|
1329
|
+
*/
|
|
1330
|
+
function populateTriggers(session, definitions) {
|
|
1331
|
+
const keys = definitions.map((definition) => definition.key);
|
|
1332
|
+
const problems = definitions.flatMap((definition) => triggerReferenceProblems(session, definition, keys));
|
|
1333
|
+
if (problems.length > 0) throw new InvalidWorldError(`the triggers have ${problems.length} problem(s)`, problems.map((message) => ({
|
|
1334
|
+
path: TRIGGERS_FILE_NAME,
|
|
1335
|
+
message
|
|
1336
|
+
})));
|
|
1337
|
+
for (const definition of definitions) session.triggers.add(definition, "world", 0);
|
|
1338
|
+
}
|
|
1339
|
+
//#endregion
|
|
1340
|
+
//#region src/host/worlds/validated-world.ts
|
|
1341
|
+
/**
|
|
1342
|
+
* Reads everything a world's files hold and checks it all as a session start does: every file reads, and what refers to something refers to something that is there.
|
|
1343
|
+
* @throws {InvalidWorldError} naming every problem of the first part of the world that has any.
|
|
1344
|
+
*/
|
|
1345
|
+
async function loadValidatedWorld(world) {
|
|
1346
|
+
const { characters, problems } = await loadCharacters(world.directory);
|
|
1347
|
+
if (problems.length > 0) throw new InvalidWorldError(`the characters of "${world.summary.name}" have ${problems.length} problem(s)`, problems);
|
|
1348
|
+
const { factions, problems: factionFileProblems } = await loadFactions(world.directory);
|
|
1349
|
+
if (factionFileProblems.length > 0) throw new InvalidWorldError(`the factions of "${world.summary.name}" have ${factionFileProblems.length} problem(s)`, factionFileProblems);
|
|
1350
|
+
const factionReferences = factionProblems(factions, characters);
|
|
1351
|
+
if (factionReferences.length > 0) throw new InvalidWorldError(`the factions of "${world.summary.name}" have ${factionReferences.length} problem(s)`, factionReferences.map((message) => ({
|
|
1352
|
+
path: world.directory,
|
|
1353
|
+
message
|
|
1354
|
+
})));
|
|
1355
|
+
const { locations, problems: locationProblems } = await loadLocations(world.directory);
|
|
1356
|
+
if (locationProblems.length > 0) throw new InvalidWorldError(`the places of "${world.summary.name}" have ${locationProblems.length} problem(s)`, locationProblems);
|
|
1357
|
+
const placing = startingPlaceProblems(characters, locations);
|
|
1358
|
+
if (placing.length > 0) throw new InvalidWorldError(`the starting places of "${world.summary.name}" have ${placing.length} problem(s)`, placing.map((message) => ({
|
|
1359
|
+
path: world.directory,
|
|
1360
|
+
message
|
|
1361
|
+
})));
|
|
1362
|
+
const { calendar, problems: calendarProblems } = await loadCalendar(world.directory);
|
|
1363
|
+
if (calendarProblems.length > 0) throw new InvalidWorldError(`the calendar of "${world.summary.name}" has ${calendarProblems.length} problem(s)`, calendarProblems);
|
|
1364
|
+
const dice = await loadDice(world.directory);
|
|
1365
|
+
if (dice.problems.length > 0) throw new InvalidWorldError(`the dice checks of "${world.summary.name}" have ${dice.problems.length} problem(s)`, dice.problems);
|
|
1366
|
+
const days = routineProblems(characters, locations, calendar);
|
|
1367
|
+
if (days.length > 0) throw new InvalidWorldError(`the days of the characters of "${world.summary.name}" have ${days.length} problem(s)`, days.map((message) => ({
|
|
1368
|
+
path: world.directory,
|
|
1369
|
+
message
|
|
1370
|
+
})));
|
|
1371
|
+
const { items, slots, problems: itemProblems } = await loadItems(world.directory, {
|
|
1372
|
+
characters: characters.map((character) => character.id),
|
|
1373
|
+
locations
|
|
1374
|
+
});
|
|
1375
|
+
if (itemProblems.length > 0) throw new InvalidWorldError(`the items of "${world.summary.name}" have ${itemProblems.length} problem(s)`, itemProblems);
|
|
1376
|
+
const authoredLore = await loadLore(world.directory);
|
|
1377
|
+
if (authoredLore.problems.length > 0) throw new InvalidWorldError(`the lore of "${world.summary.name}" has ${authoredLore.problems.length} problem(s)`, authoredLore.problems);
|
|
1378
|
+
const loreReferences = loreProblems(authoredLore.lore, {
|
|
1379
|
+
characters,
|
|
1380
|
+
factions,
|
|
1381
|
+
locations,
|
|
1382
|
+
items
|
|
1383
|
+
});
|
|
1384
|
+
if (loreReferences.length > 0) throw new InvalidWorldError(`the lore of "${world.summary.name}" has ${loreReferences.length} invalid reference(s)`, loreReferences.map((message) => ({
|
|
1385
|
+
path: world.directory,
|
|
1386
|
+
message
|
|
1387
|
+
})));
|
|
1388
|
+
const knowing = knowledgeProblems(characters, locations, items, authoredLore.lore);
|
|
1389
|
+
if (knowing.length > 0) throw new InvalidWorldError(`the starting knowledge of "${world.summary.name}" has ${knowing.length} problem(s)`, knowing.map((message) => ({
|
|
1390
|
+
path: world.directory,
|
|
1391
|
+
message
|
|
1392
|
+
})));
|
|
1393
|
+
const declared = await loadVariables(world.directory);
|
|
1394
|
+
if (declared.problems.length > 0) throw new InvalidWorldError(`the variables of "${world.summary.name}" have ${declared.problems.length} problem(s)`, declared.problems);
|
|
1395
|
+
const commandFile = await loadCommands(world.directory);
|
|
1396
|
+
if (commandFile.problems.length > 0) throw new InvalidWorldError(`the commands of "${world.summary.name}" have ${commandFile.problems.length} problem(s)`, commandFile.problems);
|
|
1397
|
+
const own = new Set(declared.defs.map((def) => def.key));
|
|
1398
|
+
const clashing = commandFile.commands.filter((command) => own.has(commandVariable(command)));
|
|
1399
|
+
if (clashing.length > 0) throw new InvalidWorldError(`the commands of "${world.summary.name}" have ${clashing.length} problem(s)`, clashing.map((command) => ({
|
|
1400
|
+
path: world.directory,
|
|
1401
|
+
message: `/${command.word} raises the flag ${commandVariable(command)}, which variables.json declares too: remove one`
|
|
1402
|
+
})));
|
|
1403
|
+
declared.defs = [...declared.defs, ...commandFile.commands.map(commandFlag)];
|
|
1404
|
+
const tracking = variableProblems({
|
|
1405
|
+
defs: declared.defs,
|
|
1406
|
+
characters,
|
|
1407
|
+
items,
|
|
1408
|
+
locations,
|
|
1409
|
+
values: world.variables
|
|
1410
|
+
});
|
|
1411
|
+
if (tracking.length > 0) throw new InvalidWorldError(`what "${world.summary.name}" tracks has ${tracking.length} problem(s)`, tracking.map((message) => ({
|
|
1412
|
+
path: world.directory,
|
|
1413
|
+
message
|
|
1414
|
+
})));
|
|
1415
|
+
const scripted = await loadTriggers(world.directory);
|
|
1416
|
+
if (scripted.problems.length > 0) throw new InvalidWorldError(`the triggers of "${world.summary.name}" have ${scripted.problems.length} problem(s)`, scripted.problems);
|
|
1417
|
+
const authoredPlots = await loadPlots(world.directory);
|
|
1418
|
+
if (authoredPlots.problems.length > 0) throw new InvalidWorldError(`the plots of "${world.summary.name}" have ${authoredPlots.problems.length} problem(s)`, authoredPlots.problems);
|
|
1419
|
+
const plotReferences = plotReferenceProblems(authoredPlots.plots, [
|
|
1420
|
+
...characters.map((entry) => entry.id),
|
|
1421
|
+
...factions.map((entry) => entry.id),
|
|
1422
|
+
...locations.map((entry) => entry.id),
|
|
1423
|
+
...items.map((entry) => entry.id),
|
|
1424
|
+
...authoredLore.lore.map((entry) => entry.id)
|
|
1425
|
+
]);
|
|
1426
|
+
if (plotReferences.length > 0) throw new InvalidWorldError(`the plots of "${world.summary.name}" have ${plotReferences.length} invalid participant(s)`, plotReferences.map((message) => ({
|
|
1427
|
+
path: world.directory,
|
|
1428
|
+
message
|
|
1429
|
+
})));
|
|
1430
|
+
const related = relationshipProblems(characters);
|
|
1431
|
+
if (related.length > 0) throw new InvalidWorldError(`the relationships of "${world.summary.name}" have ${related.length} problem(s)`, related.map((message) => ({
|
|
1432
|
+
path: world.directory,
|
|
1433
|
+
message
|
|
1434
|
+
})));
|
|
1435
|
+
return {
|
|
1436
|
+
characters,
|
|
1437
|
+
factions,
|
|
1438
|
+
locations,
|
|
1439
|
+
items,
|
|
1440
|
+
slots,
|
|
1441
|
+
authoredLore,
|
|
1442
|
+
declared,
|
|
1443
|
+
scripted,
|
|
1444
|
+
authoredPlots,
|
|
1445
|
+
calendar,
|
|
1446
|
+
checks: dice.checks,
|
|
1447
|
+
commands: commandFile.commands
|
|
1448
|
+
};
|
|
1449
|
+
}
|
|
1450
|
+
//#endregion
|
|
1451
|
+
//#region src/host/worlds/world-check.ts
|
|
1452
|
+
/** The most problems listed at once: the rest are named by their number. */
|
|
1453
|
+
const LISTED = 40;
|
|
1454
|
+
/**
|
|
1455
|
+
* Whether a session could be started from the world as its files are now, and if not why, in the words a person or an assistant can act on. Starting a session runs the same
|
|
1456
|
+
* check; it names the problems of the first part of the world that has any (characters, factions, places, calendar, dice, items, lore, tracked values, triggers, plots), so
|
|
1457
|
+
* fixing those can show the next part's.
|
|
1458
|
+
*/
|
|
1459
|
+
async function checkWorld(world) {
|
|
1460
|
+
try {
|
|
1461
|
+
await loadValidatedWorld(world);
|
|
1462
|
+
return {
|
|
1463
|
+
ok: true,
|
|
1464
|
+
problems: [],
|
|
1465
|
+
more: 0
|
|
1466
|
+
};
|
|
1467
|
+
} catch (error) {
|
|
1468
|
+
if (!(error instanceof InvalidWorldError)) throw error;
|
|
1469
|
+
const problems = error.problems.map((problem) => ({
|
|
1470
|
+
where: relative(world.directory, problem.path) || "(the world)",
|
|
1471
|
+
message: problem.message
|
|
1472
|
+
}));
|
|
1473
|
+
return {
|
|
1474
|
+
ok: false,
|
|
1475
|
+
summary: error.message,
|
|
1476
|
+
problems: problems.slice(0, LISTED),
|
|
1477
|
+
more: Math.max(0, problems.length - LISTED)
|
|
1478
|
+
};
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
//#endregion
|
|
1482
|
+
//#region src/host/import/casting.ts
|
|
1483
|
+
const CASTING_SCHEMA = {
|
|
1484
|
+
type: "object",
|
|
1485
|
+
properties: {
|
|
1486
|
+
commands: {
|
|
1487
|
+
type: "array",
|
|
1488
|
+
items: {
|
|
1489
|
+
type: "object",
|
|
1490
|
+
properties: {
|
|
1491
|
+
word: { type: "string" },
|
|
1492
|
+
description: { type: "string" }
|
|
1493
|
+
},
|
|
1494
|
+
required: ["word", "description"],
|
|
1495
|
+
additionalProperties: false
|
|
1496
|
+
}
|
|
1497
|
+
},
|
|
1498
|
+
mechanisms: {
|
|
1499
|
+
type: "array",
|
|
1500
|
+
items: {
|
|
1501
|
+
type: "object",
|
|
1502
|
+
properties: {
|
|
1503
|
+
name: { type: "string" },
|
|
1504
|
+
command: { type: "string" },
|
|
1505
|
+
happens: { type: "string" },
|
|
1506
|
+
need: { type: "string" },
|
|
1507
|
+
text: { type: "string" },
|
|
1508
|
+
options: {
|
|
1509
|
+
type: "array",
|
|
1510
|
+
items: { type: "string" }
|
|
1511
|
+
}
|
|
1512
|
+
},
|
|
1513
|
+
required: [
|
|
1514
|
+
"name",
|
|
1515
|
+
"command",
|
|
1516
|
+
"happens",
|
|
1517
|
+
"need",
|
|
1518
|
+
"text",
|
|
1519
|
+
"options"
|
|
1520
|
+
],
|
|
1521
|
+
additionalProperties: false
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
},
|
|
1525
|
+
required: ["commands", "mechanisms"],
|
|
1526
|
+
additionalProperties: false
|
|
1527
|
+
};
|
|
1528
|
+
/** A trigger key is ASCII: the name's own letters when it has any, else the mechanism's number. */
|
|
1529
|
+
const asciiKey = (name, number) => {
|
|
1530
|
+
const key = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40);
|
|
1531
|
+
return key === "" ? `casting_${number}` : key;
|
|
1532
|
+
};
|
|
1533
|
+
const str = (value) => typeof value === "string" ? value.trim() : "";
|
|
1534
|
+
const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null) : [];
|
|
1535
|
+
/** The most of the card's casting passages one request reads. */
|
|
1536
|
+
const BUDGET_CHARS = 14e3;
|
|
1537
|
+
const MAX_MECHANISMS = 8;
|
|
1538
|
+
/**
|
|
1539
|
+
* The documents of `commands.json` and `triggers.json` an answer describes: a command raises the flag its trigger waits on, a happening is a statement the story is judged
|
|
1540
|
+
* against, and the trigger has the world author make the person (a drawn option when the card gives a list). What does not read as a valid file is left out, with a note.
|
|
1541
|
+
*/
|
|
1542
|
+
/** Whether the passages name `word` as something the player types: after a slash, or alone in brackets or quotes. A word that only turns up in the card's sentences is a topic, not a command. */
|
|
1543
|
+
function namedAsCommand(word, passages) {
|
|
1544
|
+
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1545
|
+
return new RegExp(`/${escaped}(?![\\p{L}\\p{N}_])|[「『【\\[“"'‘((]\\s*/?${escaped}\\s*[」』】\\]”"'’))]`, "iu").test(passages.join("\n"));
|
|
1546
|
+
}
|
|
1547
|
+
function castingDocuments(answer, passages = []) {
|
|
1548
|
+
const notes = [];
|
|
1549
|
+
const keyed = objects(answer["commands"]).map((entry) => ({
|
|
1550
|
+
word: str(entry["word"]).toLowerCase().replace(/^\//, ""),
|
|
1551
|
+
description: str(entry["description"])
|
|
1552
|
+
})).filter((entry) => entry.word !== "" && entry.description !== "" && namedAsCommand(entry.word, passages)).map((entry, index) => ({
|
|
1553
|
+
...entry,
|
|
1554
|
+
key: /^[a-z][a-z0-9_]{0,29}$/.test(entry.word) ? entry.word : `word_${index + 1}`
|
|
1555
|
+
}));
|
|
1556
|
+
const parsedCommands = parseCommandsFile(JSON.stringify({ commands: keyed.map((entry) => ({
|
|
1557
|
+
word: entry.word,
|
|
1558
|
+
key: entry.key,
|
|
1559
|
+
description: entry.description
|
|
1560
|
+
})) }));
|
|
1561
|
+
const usable = parsedCommands.ok ? parsedCommands.value : [];
|
|
1562
|
+
if (!parsedCommands.ok) notes.push(`commands not carried: ${parsedCommands.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ")}`);
|
|
1563
|
+
const taken = /* @__PURE__ */ new Set();
|
|
1564
|
+
const triggers = [];
|
|
1565
|
+
for (const mechanism of objects(answer["mechanisms"]).slice(0, MAX_MECHANISMS)) {
|
|
1566
|
+
const name = str(mechanism["name"]);
|
|
1567
|
+
const command = usable.find((entry) => entry.word === str(mechanism["command"]).toLowerCase());
|
|
1568
|
+
const happens = str(mechanism["happens"]) || (command === void 0 && str(mechanism["command"]) !== "" ? str(mechanism["name"]) : "");
|
|
1569
|
+
const need = str(mechanism["need"]);
|
|
1570
|
+
const options = Array.isArray(mechanism["options"]) ? mechanism["options"].map(str).filter((option) => option !== "") : [];
|
|
1571
|
+
let words = str(mechanism["text"]) || need;
|
|
1572
|
+
if (name === "" || need === "" || command === void 0 && happens === "") {
|
|
1573
|
+
notes.push(`casting not carried: "${name || "unnamed"}" has no reason to start it`);
|
|
1574
|
+
continue;
|
|
1575
|
+
}
|
|
1576
|
+
if (options.length > 0 && !words.includes("[draw]")) words = `${words} [draw]`;
|
|
1577
|
+
if (options.length === 0) words = words.replaceAll("[draw]", "").trim();
|
|
1578
|
+
const when = command === void 0 ? {
|
|
1579
|
+
type: "judged",
|
|
1580
|
+
text: happens
|
|
1581
|
+
} : {
|
|
1582
|
+
type: "variable",
|
|
1583
|
+
variable: commandFlagKey(command),
|
|
1584
|
+
op: COMPARISONS[0],
|
|
1585
|
+
value: true
|
|
1586
|
+
};
|
|
1587
|
+
triggers.push({
|
|
1588
|
+
key: uniqueKey(asciiKey(name, triggers.length + 1), taken),
|
|
1589
|
+
name,
|
|
1590
|
+
when,
|
|
1591
|
+
repeat: true,
|
|
1592
|
+
effects: [{
|
|
1593
|
+
type: "beat",
|
|
1594
|
+
dispatch: "author",
|
|
1595
|
+
need,
|
|
1596
|
+
text: words,
|
|
1597
|
+
...options.length === 0 ? {} : { draw: options }
|
|
1598
|
+
}]
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
const parsedTriggers = parseTriggersFile(JSON.stringify(triggers));
|
|
1602
|
+
if (!parsedTriggers.ok) {
|
|
1603
|
+
notes.push(`casting not carried: ${parsedTriggers.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ")}`);
|
|
1604
|
+
return {
|
|
1605
|
+
commands: [],
|
|
1606
|
+
triggers: [],
|
|
1607
|
+
notes
|
|
1608
|
+
};
|
|
1609
|
+
}
|
|
1610
|
+
const used = new Set(triggers.flatMap((trigger) => trigger["when"]["variable"] === void 0 ? [] : [String(trigger["when"]["variable"])]));
|
|
1611
|
+
return {
|
|
1612
|
+
commands: usable.filter((command) => used.has(commandFlagKey(command))).map((command) => ({ ...command })),
|
|
1613
|
+
triggers,
|
|
1614
|
+
notes
|
|
1615
|
+
};
|
|
1616
|
+
}
|
|
1617
|
+
/** Turns what the card says about making people up into the world's commands and the triggers that have the world author make them. */
|
|
1618
|
+
async function extractCasting(ctx, card, passages) {
|
|
1619
|
+
if (passages.length === 0) return {
|
|
1620
|
+
commands: [],
|
|
1621
|
+
triggers: [],
|
|
1622
|
+
notes: []
|
|
1623
|
+
};
|
|
1624
|
+
ctx.say("turning the casting guidance into commands and triggers");
|
|
1625
|
+
try {
|
|
1626
|
+
const tr = trOf(ctx);
|
|
1627
|
+
const prompt = `${tr("Card: {name}", { name: card.name })}\n\n${tr("Passages about making people up:")}\n\n${passages.join("\n\n---\n\n").slice(0, BUDGET_CHARS)}`;
|
|
1628
|
+
return castingDocuments(await ctx.run({
|
|
1629
|
+
persona: ctx.text("import/casting", { rules: ctx.text("import/common-rules") }),
|
|
1630
|
+
maxTokens: 3e3,
|
|
1631
|
+
prompt,
|
|
1632
|
+
result: CASTING_SCHEMA,
|
|
1633
|
+
check: (value) => {
|
|
1634
|
+
const made = castingDocuments(value, passages);
|
|
1635
|
+
return made.triggers.length === 0 && made.notes.length > 0 ? made.notes.join("; ") : void 0;
|
|
1636
|
+
}
|
|
1637
|
+
}), passages);
|
|
1638
|
+
} catch (error) {
|
|
1639
|
+
return {
|
|
1640
|
+
commands: [],
|
|
1641
|
+
triggers: [],
|
|
1642
|
+
notes: [`the casting guidance was not turned into commands and triggers: ${error instanceof Error ? error.message : String(error)}`]
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
//#endregion
|
|
1647
|
+
//#region src/host/lorebooks/lorebooks.ts
|
|
1648
|
+
const LOREBOOKS_FOLDER = "lorebooks";
|
|
1649
|
+
const LOREBOOK_FILE = "lorebook.json";
|
|
1650
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
1651
|
+
const ENTRY_ID = /^[\p{L}\p{N}][\p{L}\p{N}_-]{0,79}$/u;
|
|
1652
|
+
const MAX_TEXT = 300;
|
|
1653
|
+
const isLorebookName = (name) => NAME.test(name);
|
|
1654
|
+
const isEntryId = (id) => ENTRY_ID.test(id);
|
|
1655
|
+
const lorebooksDirectory = (root) => join(root, LOREBOOKS_FOLDER);
|
|
1656
|
+
function lorebookDirectory(root, name) {
|
|
1657
|
+
if (!isLorebookName(name)) throw new Error(`"${name}" is not a usable lorebook name (letters, digits, "-" and "_", up to 64)`);
|
|
1658
|
+
return join(lorebooksDirectory(root), name);
|
|
1659
|
+
}
|
|
1660
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1661
|
+
function parseHeader(value, problems) {
|
|
1662
|
+
if (!isRecord$1(value)) {
|
|
1663
|
+
problems.push(`${LOREBOOK_FILE} must be an object`);
|
|
1664
|
+
return {};
|
|
1665
|
+
}
|
|
1666
|
+
const text = (key) => {
|
|
1667
|
+
const field = value[key];
|
|
1668
|
+
if (field === void 0 || field === null) return void 0;
|
|
1669
|
+
if (typeof field !== "string" || field.length > MAX_TEXT) {
|
|
1670
|
+
problems.push(`${LOREBOOK_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
|
|
1671
|
+
return;
|
|
1672
|
+
}
|
|
1673
|
+
return field.trim() || void 0;
|
|
1674
|
+
};
|
|
1675
|
+
const title = text("title");
|
|
1676
|
+
const description = text("description");
|
|
1677
|
+
return {
|
|
1678
|
+
...title === void 0 ? {} : { title },
|
|
1679
|
+
...description === void 0 ? {} : { description }
|
|
1680
|
+
};
|
|
1681
|
+
}
|
|
1682
|
+
function readHeader(directory, problems) {
|
|
1683
|
+
const file = join(directory, LOREBOOK_FILE);
|
|
1684
|
+
if (!existsSync(file)) return {};
|
|
1685
|
+
let value;
|
|
1686
|
+
try {
|
|
1687
|
+
value = JSON.parse(readFileSync(file, "utf8"));
|
|
1688
|
+
} catch {
|
|
1689
|
+
problems.push(`${LOREBOOK_FILE} is not valid JSON`);
|
|
1690
|
+
return {};
|
|
1691
|
+
}
|
|
1692
|
+
return parseHeader(value, problems);
|
|
1693
|
+
}
|
|
1694
|
+
/** What is wrong with the entries of a book as a whole: an entry about a character or place of some world, or relating to one that is not there. */
|
|
1695
|
+
function bookProblems(entries) {
|
|
1696
|
+
const ids = new Set(entries.map((entry) => entry.id));
|
|
1697
|
+
return entries.flatMap((entry) => [...entry.subjects.length > 0 ? [`${entry.id}: a lorebook does not belong to a world, so its entries have no subjects`] : [], ...entry.related.flatMap((other) => other === entry.id ? [`${entry.id}: related: an entry cannot relate to itself`] : ids.has(other) ? [] : [`${entry.id}: related: "${other}" is not an entry of this book`])]);
|
|
1698
|
+
}
|
|
1699
|
+
/** Reads one lorebook folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
|
|
1700
|
+
async function readLorebook(directory, name) {
|
|
1701
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1702
|
+
const problems = [];
|
|
1703
|
+
const header = readHeader(directory, problems);
|
|
1704
|
+
const { lore, problems: found } = await loadLore(directory);
|
|
1705
|
+
for (const problem of found) problems.push(`${problem.path.slice(directory.length + 1)}: ${problem.message}`);
|
|
1706
|
+
problems.push(...bookProblems(lore));
|
|
1707
|
+
if (lore.length === 0 && problems.length === 0) problems.push("the lorebook has no entries");
|
|
1708
|
+
return {
|
|
1709
|
+
summary: {
|
|
1710
|
+
name,
|
|
1711
|
+
title: header.title ?? name,
|
|
1712
|
+
description: header.description ?? "",
|
|
1713
|
+
entries: lore.length,
|
|
1714
|
+
common: lore.filter((entry) => entry.scope === "everyone").length,
|
|
1715
|
+
problems
|
|
1716
|
+
},
|
|
1717
|
+
entries: lore.sort((a, b) => a.title.localeCompare(b.title))
|
|
1718
|
+
};
|
|
1719
|
+
}
|
|
1720
|
+
async function listLorebooks(root) {
|
|
1721
|
+
const folder = lorebooksDirectory(root);
|
|
1722
|
+
if (!existsSync(folder)) return [];
|
|
1723
|
+
const found = (await readdir(folder, { withFileTypes: true })).filter((entry) => entry.isDirectory() && isLorebookName(entry.name));
|
|
1724
|
+
return (await Promise.all(found.map((entry) => readLorebook(join(folder, entry.name), entry.name)))).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
|
|
1725
|
+
}
|
|
1726
|
+
async function loadLorebook(root, name) {
|
|
1727
|
+
return await readLorebook(lorebookDirectory(root, name), name);
|
|
1728
|
+
}
|
|
1729
|
+
const toEntry = (definition) => ({
|
|
1730
|
+
id: definition.id,
|
|
1731
|
+
title: definition.title,
|
|
1732
|
+
kind: definition.kind,
|
|
1733
|
+
scope: definition.scope,
|
|
1734
|
+
knownBy: definition.knownBy,
|
|
1735
|
+
summary: definition.summary,
|
|
1736
|
+
body: definition.body,
|
|
1737
|
+
related: definition.related
|
|
1738
|
+
});
|
|
1739
|
+
const entriesOf = (book) => book.entries.map(toEntry);
|
|
1740
|
+
function headerFile(header) {
|
|
1741
|
+
return `${JSON.stringify(header, null, 2)}\n`;
|
|
1742
|
+
}
|
|
1743
|
+
async function writeAtomic(file, text) {
|
|
1744
|
+
await mkdir(dirname(file), { recursive: true });
|
|
1745
|
+
await writeFile(`${file}.tmp`, text);
|
|
1746
|
+
await rename(`${file}.tmp`, file);
|
|
1747
|
+
}
|
|
1748
|
+
/** Makes an empty lorebook. @throws {Error} when the name is taken or the information is not acceptable. */
|
|
1749
|
+
async function createLorebook(root, request) {
|
|
1750
|
+
const target = lorebookDirectory(root, request.name);
|
|
1751
|
+
if (existsSync(target)) throw new Error(`there is already a lorebook "${request.name}"`);
|
|
1752
|
+
const problems = [];
|
|
1753
|
+
const header = parseHeader({
|
|
1754
|
+
title: request.title?.trim(),
|
|
1755
|
+
description: request.description?.trim()
|
|
1756
|
+
}, problems);
|
|
1757
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
1758
|
+
await writeAtomic(join(target, LOREBOOK_FILE), headerFile(header));
|
|
1759
|
+
return await readLorebook(target, request.name);
|
|
1760
|
+
}
|
|
1761
|
+
/** Makes an empty folder that an import is about to fill; it has no entries yet, so it reads as having problems until it does. */
|
|
1762
|
+
async function reserveLorebook(root, name, title) {
|
|
1763
|
+
const target = lorebookDirectory(root, name);
|
|
1764
|
+
if (existsSync(target)) throw new Error(`there is already a lorebook "${name}"`);
|
|
1765
|
+
await writeAtomic(join(target, LOREBOOK_FILE), headerFile({ title: title.trim().slice(0, MAX_TEXT) || name }));
|
|
1766
|
+
return target;
|
|
1767
|
+
}
|
|
1768
|
+
/** Changes what a lorebook says about itself. @throws {Error} when the lorebook does not exist or the change is not acceptable; nothing is written then. */
|
|
1769
|
+
async function updateLorebookInfo(root, name, change) {
|
|
1770
|
+
const directory = lorebookDirectory(root, name);
|
|
1771
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1772
|
+
const current = readHeader(directory, []);
|
|
1773
|
+
const problems = [];
|
|
1774
|
+
const next = parseHeader({
|
|
1775
|
+
title: change.title ?? current.title,
|
|
1776
|
+
description: change.description ?? current.description
|
|
1777
|
+
}, problems);
|
|
1778
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
1779
|
+
await writeAtomic(join(directory, LOREBOOK_FILE), headerFile(next));
|
|
1780
|
+
return await readLorebook(directory, name);
|
|
1781
|
+
}
|
|
1782
|
+
/** The file of an entry: written in the format of a world's own lore, with its scope always said. */
|
|
1783
|
+
function entryFile(entry) {
|
|
1784
|
+
return `${JSON.stringify({
|
|
1785
|
+
title: entry.title,
|
|
1786
|
+
kind: entry.kind,
|
|
1787
|
+
scope: entry.scope,
|
|
1788
|
+
...entry.scope === "listed" && entry.knownBy.length > 0 ? { known_by: entry.knownBy } : {},
|
|
1789
|
+
summary: entry.summary,
|
|
1790
|
+
body: entry.body,
|
|
1791
|
+
...entry.related.length > 0 ? { related: entry.related } : {}
|
|
1792
|
+
}, null, 2)}\n`;
|
|
1793
|
+
}
|
|
1794
|
+
/** Checks an entry the way a story start would, before anything is written. @returns why it cannot be used, or nothing. */
|
|
1795
|
+
function entryProblem(entry) {
|
|
1796
|
+
if (!isEntryId(entry.id)) return `"${entry.id}" is not a usable entry id (letters, digits, "-" and "_", up to 80)`;
|
|
1797
|
+
if (!LORE_KINDS.includes(entry.kind)) return `kind must be one of ${LORE_KINDS.join(", ")}`;
|
|
1798
|
+
if (!LORE_SCOPES.includes(entry.scope)) return `scope must be one of ${LORE_SCOPES.join(", ")}`;
|
|
1799
|
+
if (entry.title.trim() === "") return "the entry needs a title";
|
|
1800
|
+
if (entry.body.trim() === "" && entry.summary.trim() === "") return "the entry needs a summary or a body";
|
|
1801
|
+
const parsed = parseLoreFile(entryFile({
|
|
1802
|
+
...entry,
|
|
1803
|
+
title: entry.title.trim()
|
|
1804
|
+
}), entry.id);
|
|
1805
|
+
return parsed.ok ? void 0 : parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
|
|
1806
|
+
}
|
|
1807
|
+
/**
|
|
1808
|
+
* Creates several new entries of a lorebook at once, each checked as `writeLorebookEntry` checks one; none is written when any is not acceptable.
|
|
1809
|
+
* @throws {Error} when the lorebook does not exist, an id is taken or an entry is not acceptable, or the book would have more entries than a world may.
|
|
1810
|
+
*/
|
|
1811
|
+
async function addLorebookEntries(root, name, entries) {
|
|
1812
|
+
const directory = lorebookDirectory(root, name);
|
|
1813
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1814
|
+
const book = await readLorebook(directory, name);
|
|
1815
|
+
if (book.entries.length + entries.length > 500) throw new Error(`a lorebook has at most 500 entries`);
|
|
1816
|
+
const ids = new Set(book.entries.map((entry) => entry.id));
|
|
1817
|
+
for (const entry of entries) {
|
|
1818
|
+
const problem = entryProblem(entry);
|
|
1819
|
+
if (problem !== void 0) throw new Error(`entry "${entry.title}": ${problem}`);
|
|
1820
|
+
if (ids.has(entry.id)) throw new Error(`there is already an entry "${entry.id}"`);
|
|
1821
|
+
ids.add(entry.id);
|
|
1822
|
+
}
|
|
1823
|
+
for (const entry of entries) await writeAtomic(join(directory, LORE_DIR, entry.id, LORE_FILE_NAME), entryFile({
|
|
1824
|
+
...entry,
|
|
1825
|
+
title: entry.title.trim()
|
|
1826
|
+
}));
|
|
1827
|
+
return await readLorebook(directory, name);
|
|
1828
|
+
}
|
|
1829
|
+
/** Creates or replaces one entry. @throws {Error} when the lorebook does not exist, the entry is not acceptable or the book would have more entries than a world may. */
|
|
1830
|
+
async function writeLorebookEntry(root, name, entry) {
|
|
1831
|
+
const directory = lorebookDirectory(root, name);
|
|
1832
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1833
|
+
const problem = entryProblem(entry);
|
|
1834
|
+
if (problem !== void 0) throw new Error(problem);
|
|
1835
|
+
const file = join(directory, LORE_DIR, entry.id, LORE_FILE_NAME);
|
|
1836
|
+
const book = await readLorebook(directory, name);
|
|
1837
|
+
if (!existsSync(file) && book.entries.length >= 500) throw new Error(`a lorebook has at most 500 entries`);
|
|
1838
|
+
const others = book.entries.filter((other) => other.id !== entry.id);
|
|
1839
|
+
const missing = entry.related.filter((id) => id === entry.id || !others.some((other) => other.id === id));
|
|
1840
|
+
if (missing.length > 0) throw new Error(`related: ${missing.map((id) => `"${id}"`).join(", ")} ${missing.length === 1 ? "is" : "are"} not (other) entries of this book`);
|
|
1841
|
+
await writeAtomic(file, entryFile({
|
|
1842
|
+
...entry,
|
|
1843
|
+
title: entry.title.trim()
|
|
1844
|
+
}));
|
|
1845
|
+
return await readLorebook(directory, name);
|
|
1846
|
+
}
|
|
1847
|
+
/** Moves an entry into the book's `.trash`. @throws {Error} when it does not exist or other entries relate to it. */
|
|
1848
|
+
async function deleteLorebookEntry(root, name, id, now = Date.now) {
|
|
1849
|
+
const directory = lorebookDirectory(root, name);
|
|
1850
|
+
const folder = join(directory, LORE_DIR, id);
|
|
1851
|
+
if (!isEntryId(id) || !existsSync(join(folder, "lore.json"))) throw new Error(`the lorebook "${name}" has no entry "${id}"`);
|
|
1852
|
+
const citing = (await readLorebook(directory, name)).entries.filter((entry) => entry.id !== id && entry.related.includes(id)).map((entry) => entry.id);
|
|
1853
|
+
if (citing.length > 0) throw new Error(`the entries ${citing.join(", ")} relate to "${id}"; change them first`);
|
|
1854
|
+
const aside = join(directory, ".trash", LORE_DIR, `${id}-${now()}`);
|
|
1855
|
+
await mkdir(dirname(aside), { recursive: true });
|
|
1856
|
+
await rename(folder, aside);
|
|
1857
|
+
return await readLorebook(directory, name);
|
|
1858
|
+
}
|
|
1859
|
+
/** Moves a lorebook out of the library into `<root>/.trash/lorebooks/`. @returns where it went. */
|
|
1860
|
+
async function deleteLorebook(root, name, now = Date.now) {
|
|
1861
|
+
const directory = lorebookDirectory(root, name);
|
|
1862
|
+
if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
|
|
1863
|
+
const aside = join(root, ".trash", LOREBOOKS_FOLDER, `${name}-${now()}`);
|
|
1864
|
+
await mkdir(dirname(aside), { recursive: true });
|
|
1865
|
+
await rename(directory, aside);
|
|
1866
|
+
return aside;
|
|
1867
|
+
}
|
|
1868
|
+
const MAX_OPENING_CHARS = 2e4;
|
|
1869
|
+
const TEXT_FIELDS = [
|
|
1870
|
+
"name",
|
|
1871
|
+
"description",
|
|
1872
|
+
"opening",
|
|
1873
|
+
"authorName",
|
|
1874
|
+
"authorUrl",
|
|
1875
|
+
"timeZone",
|
|
1876
|
+
"startingTime",
|
|
1877
|
+
"version",
|
|
1878
|
+
"preset"
|
|
1879
|
+
];
|
|
1880
|
+
const LIST_FIELDS = [
|
|
1881
|
+
"tags",
|
|
1882
|
+
"rules",
|
|
1883
|
+
"lorebooks"
|
|
1884
|
+
];
|
|
1885
|
+
/** Reads a body that came from the browser; every field is checked and each problem is reported. */
|
|
1886
|
+
function parseWorldInfoEdit(value) {
|
|
1887
|
+
const problems = [];
|
|
1888
|
+
const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
1889
|
+
if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
|
|
1890
|
+
const edit = {};
|
|
1891
|
+
for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "tools" && key !== "sampling") problems.push(`there is no field "${key}"`);
|
|
1892
|
+
for (const key of TEXT_FIELDS) {
|
|
1893
|
+
if (input[key] === void 0) continue;
|
|
1894
|
+
if (typeof input[key] === "string") edit[key] = input[key].trim();
|
|
1895
|
+
else problems.push(`${key} must be text`);
|
|
1896
|
+
}
|
|
1897
|
+
for (const key of LIST_FIELDS) {
|
|
1898
|
+
if (input[key] === void 0) continue;
|
|
1899
|
+
if (Array.isArray(input[key]) && input[key].every((entry) => typeof entry === "string")) edit[key] = input[key].map((entry) => entry.trim()).filter((entry) => entry !== "");
|
|
1900
|
+
else problems.push(`${key} must be a list of text`);
|
|
1901
|
+
}
|
|
1902
|
+
if (input["alternateOpenings"] !== void 0) {
|
|
1903
|
+
const list = input["alternateOpenings"];
|
|
1904
|
+
const entries = Array.isArray(list) ? list.map((entry) => typeof entry === "object" && entry !== null ? entry : void 0) : void 0;
|
|
1905
|
+
if (entries === void 0 || entries.some((entry) => entry === void 0 || typeof entry["text"] !== "string" || entry["title"] !== void 0 && typeof entry["title"] !== "string" || entry["character"] !== void 0 && typeof entry["character"] !== "string")) problems.push("alternateOpenings must be a list of { title, text, character? }");
|
|
1906
|
+
else {
|
|
1907
|
+
const kept = entries.map((entry) => ({
|
|
1908
|
+
title: String(entry["title"] ?? "").trim(),
|
|
1909
|
+
text: String(entry["text"]).trim(),
|
|
1910
|
+
...String(entry["character"] ?? "").trim() === "" ? {} : { character: String(entry["character"]).trim() }
|
|
1911
|
+
})).filter((entry) => entry.text !== "");
|
|
1912
|
+
if (kept.length > 30) problems.push(`there are more than 30 alternate openings`);
|
|
1913
|
+
if (kept.some((entry) => entry.text.length > 2e4)) problems.push(`an alternate opening is longer than ${MAX_OPENING_CHARS} characters`);
|
|
1914
|
+
edit["alternateOpenings"] = kept;
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
if (input["tools"] !== void 0) {
|
|
1918
|
+
const board = parseSwitchboard(input["tools"], "tools");
|
|
1919
|
+
if (typeof board === "string") problems.push(board);
|
|
1920
|
+
else edit["tools"] = board;
|
|
1921
|
+
}
|
|
1922
|
+
if (input["sampling"] !== void 0) edit["sampling"] = parseSampling(input["sampling"], "sampling", problems);
|
|
1923
|
+
if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
|
|
1924
|
+
if (edit["name"] === "") problems.push("the world needs a name");
|
|
1925
|
+
if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
|
|
1926
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
1927
|
+
return edit;
|
|
1928
|
+
}
|
|
1929
|
+
//#endregion
|
|
1930
|
+
//#region src/host/worlds/world-file.ts
|
|
1931
|
+
const WORLD_FILE_NAME = "world.json";
|
|
1932
|
+
/** `alternate_openings` is a list of `{ title, text, character? }`: other first messages the player may start with, each for any character or for one playable character. */
|
|
1933
|
+
function readAlternateOpenings(reader) {
|
|
1934
|
+
const value = reader.raw("alternate_openings");
|
|
1935
|
+
if (value === void 0 || value === null) return void 0;
|
|
1936
|
+
if (!Array.isArray(value)) {
|
|
1937
|
+
reader.fail("alternate_openings", "must be a list");
|
|
1938
|
+
return;
|
|
1939
|
+
}
|
|
1940
|
+
if (value.length > 30) reader.fail("alternate_openings", `has more than 30 openings`);
|
|
1941
|
+
const openings = [];
|
|
1942
|
+
for (const entry of reader.objects("alternate_openings")) {
|
|
1943
|
+
const text = entry.string("text", { required: true })?.trim();
|
|
1944
|
+
if (text === void 0 || text === "") continue;
|
|
1945
|
+
if (text.length > 2e4) entry.fail("text", `is longer than ${MAX_OPENING_CHARS} characters`);
|
|
1946
|
+
const character = entry.string("character")?.trim();
|
|
1947
|
+
openings.push({
|
|
1948
|
+
title: entry.string("title")?.trim() || text.slice(0, 40),
|
|
1949
|
+
text,
|
|
1950
|
+
...character === void 0 || character === "" ? {} : { character }
|
|
1951
|
+
});
|
|
1952
|
+
}
|
|
1953
|
+
return openings.length === 0 ? void 0 : openings;
|
|
1954
|
+
}
|
|
1955
|
+
/** `tools`: switches by kind of agent and tool name; a world carried from a version with other tools still loads. */
|
|
1956
|
+
function readTools(reader) {
|
|
1957
|
+
const value = reader.raw("tools");
|
|
1958
|
+
if (value === void 0) return void 0;
|
|
1959
|
+
const board = parseSwitchboard(value, "tools");
|
|
1960
|
+
if (typeof board === "string") {
|
|
1961
|
+
reader.fail("tools", board.replace(/^"tools"\s*/, ""));
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
return Object.keys(board).length === 0 ? void 0 : board;
|
|
1965
|
+
}
|
|
1966
|
+
/** `sampling` is an object of the controls a story's requests may carry (see `StorySampling`). */
|
|
1967
|
+
function readSampling(reader) {
|
|
1968
|
+
const problems = [];
|
|
1969
|
+
const sampling = parseSampling(reader.raw("sampling"), "sampling", problems);
|
|
1970
|
+
for (const problem of problems) reader.fail("sampling", problem.replace(/^sampling\.?/, ""));
|
|
1971
|
+
return Object.keys(sampling).length === 0 ? void 0 : sampling;
|
|
1972
|
+
}
|
|
1973
|
+
/** `rules` is one rule as text, or a list of them; blank ones are left out. */
|
|
1974
|
+
function readRules(reader) {
|
|
1975
|
+
const value = reader.raw("rules");
|
|
1976
|
+
if (value === void 0 || value === null) return void 0;
|
|
1977
|
+
const kept = (typeof value === "string" ? [value] : reader.strings("rules")).map((rule) => rule.trim()).filter((rule) => rule !== "");
|
|
1978
|
+
if (kept.length > 30) reader.fail("rules", `has more than 30 rules`);
|
|
1979
|
+
const long = kept.findIndex((rule) => rule.length > 300);
|
|
1980
|
+
if (long >= 0) reader.fail("rules", `rule ${long + 1} is longer than 300 characters: keep rules short`);
|
|
1981
|
+
return kept.length === 0 ? void 0 : kept;
|
|
1982
|
+
}
|
|
1983
|
+
/** `opening_message` is plain text (one narration), or a list of parts in the order the player reads them. */
|
|
1984
|
+
function readOpening(reader) {
|
|
1985
|
+
const value = reader.raw("opening_message");
|
|
1986
|
+
if (value === void 0 || value === null) return void 0;
|
|
1987
|
+
if (typeof value === "string") return value.trim() === "" ? void 0 : [{
|
|
1988
|
+
type: "narration",
|
|
1989
|
+
text: value.trim()
|
|
1990
|
+
}];
|
|
1991
|
+
if (!Array.isArray(value)) {
|
|
1992
|
+
reader.fail("opening_message", "must be text or a list of parts");
|
|
1993
|
+
return;
|
|
1994
|
+
}
|
|
1995
|
+
const parts = [];
|
|
1996
|
+
for (const part of reader.objects("opening_message")) {
|
|
1997
|
+
const type = part.oneOf("type", ["narration", "utterance"], "narration");
|
|
1998
|
+
const text = part.string("text", { required: true })?.trim();
|
|
1999
|
+
if (text === void 0 || text === "") continue;
|
|
2000
|
+
if (type === "narration") {
|
|
2001
|
+
parts.push({
|
|
2002
|
+
type,
|
|
2003
|
+
text
|
|
2004
|
+
});
|
|
2005
|
+
continue;
|
|
2006
|
+
}
|
|
2007
|
+
const character = part.string("character", { required: true });
|
|
2008
|
+
if (character !== void 0) parts.push({
|
|
2009
|
+
type,
|
|
2010
|
+
character,
|
|
2011
|
+
text
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
return parts.length === 0 ? void 0 : parts;
|
|
2015
|
+
}
|
|
2016
|
+
/** `time_zone` (an IANA name) and `starting_time` (an ISO 8601 date and time, in `time_zone` unless it carries an offset). */
|
|
2017
|
+
function readClock(reader) {
|
|
2018
|
+
const timeZone = reader.string("time_zone");
|
|
2019
|
+
if (timeZone !== void 0 && !isTimeZone(timeZone)) {
|
|
2020
|
+
reader.fail("time_zone", `"${timeZone}" is not a time zone: write it like Europe/London or UTC`);
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
const text = reader.string("starting_time");
|
|
2024
|
+
let startingTime;
|
|
2025
|
+
if (text !== void 0) try {
|
|
2026
|
+
startingTime = parseInstant(text, timeZone ?? "UTC");
|
|
2027
|
+
} catch (error) {
|
|
2028
|
+
reader.fail("starting_time", error instanceof Error ? error.message : String(error));
|
|
2029
|
+
return;
|
|
2030
|
+
}
|
|
2031
|
+
return timeZone === void 0 && startingTime === void 0 ? void 0 : {
|
|
2032
|
+
...startingTime === void 0 ? {} : { startingTime },
|
|
2033
|
+
...timeZone === void 0 ? {} : { timeZone }
|
|
2034
|
+
};
|
|
2035
|
+
}
|
|
2036
|
+
function readAuthor(reader) {
|
|
2037
|
+
if (reader === void 0) return void 0;
|
|
2038
|
+
const name = reader.string("name", { required: true });
|
|
2039
|
+
const url = reader.string("url");
|
|
2040
|
+
return name === void 0 ? void 0 : {
|
|
2041
|
+
name,
|
|
2042
|
+
...url === void 0 ? {} : { url }
|
|
2043
|
+
};
|
|
2044
|
+
}
|
|
2045
|
+
function parseWorldFile(text) {
|
|
2046
|
+
const issues = [];
|
|
2047
|
+
const reader = Reader.fromJson(text, issues);
|
|
2048
|
+
if (reader === void 0) return {
|
|
2049
|
+
ok: false,
|
|
2050
|
+
issues
|
|
2051
|
+
};
|
|
2052
|
+
const id = readIdentifier(reader);
|
|
2053
|
+
const name = reader.string("name", { required: true });
|
|
2054
|
+
const description = reader.text("description");
|
|
2055
|
+
const tags = reader.object("metadata")?.strings("tags") ?? [];
|
|
2056
|
+
const author = readAuthor(reader.object("author"));
|
|
2057
|
+
const rawVersion = reader.raw("version");
|
|
2058
|
+
if (rawVersion !== void 0 && rawVersion !== null && typeof rawVersion !== "string" && typeof rawVersion !== "number") reader.fail("version", "must be text or a number");
|
|
2059
|
+
const version = (typeof rawVersion === "string" || typeof rawVersion === "number" ? String(rawVersion).trim() : "") || void 0;
|
|
2060
|
+
if (version !== void 0 && version.length > 40) reader.fail("version", `is longer than 40 characters`);
|
|
2061
|
+
const coverMediaId = reader.string("cover_media_id");
|
|
2062
|
+
const opening = readOpening(reader);
|
|
2063
|
+
const clock = readClock(reader);
|
|
2064
|
+
const variables = readVariableValues(reader);
|
|
2065
|
+
const rules = readRules(reader);
|
|
2066
|
+
const tools = readTools(reader);
|
|
2067
|
+
const alternateOpenings = readAlternateOpenings(reader);
|
|
2068
|
+
const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
|
|
2069
|
+
const sampling = readSampling(reader);
|
|
2070
|
+
const preset = reader.string("preset")?.trim() || void 0;
|
|
2071
|
+
if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
|
|
2072
|
+
const lorebooks = reader.strings("lorebooks").map((entry) => entry.trim()).filter((entry) => entry !== "");
|
|
2073
|
+
for (const [index, entry] of lorebooks.entries()) if (!isLorebookName(entry)) reader.fail(`lorebooks[${index}]`, "must be the name of a lorebook: letters, digits, \"-\" and \"_\"");
|
|
2074
|
+
if (name === void 0 || issues.length > 0) return {
|
|
2075
|
+
ok: false,
|
|
2076
|
+
issues
|
|
2077
|
+
};
|
|
2078
|
+
return {
|
|
2079
|
+
ok: true,
|
|
2080
|
+
value: {
|
|
2081
|
+
...id === void 0 ? {} : { id },
|
|
2082
|
+
name,
|
|
2083
|
+
description,
|
|
2084
|
+
tags,
|
|
2085
|
+
...author === void 0 ? {} : { author },
|
|
2086
|
+
...version === void 0 ? {} : { version },
|
|
2087
|
+
...coverMediaId === void 0 ? {} : { coverMediaId },
|
|
2088
|
+
...opening === void 0 ? {} : { opening },
|
|
2089
|
+
...clock === void 0 ? {} : { clock },
|
|
2090
|
+
...variables === void 0 ? {} : { variables },
|
|
2091
|
+
...rules === void 0 ? {} : { rules },
|
|
2092
|
+
...tools === void 0 ? {} : { tools },
|
|
2093
|
+
...alternateOpenings === void 0 ? {} : { alternateOpenings },
|
|
2094
|
+
...narrationVoice === void 0 ? {} : { narrationVoice },
|
|
2095
|
+
...sampling === void 0 ? {} : { sampling },
|
|
2096
|
+
...preset === void 0 ? {} : { preset },
|
|
2097
|
+
...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
|
|
2098
|
+
}
|
|
2099
|
+
};
|
|
2100
|
+
}
|
|
2101
|
+
//#endregion
|
|
2102
|
+
//#region src/host/worlds/world-file-io.ts
|
|
2103
|
+
const queues = /* @__PURE__ */ new Map();
|
|
2104
|
+
/**
|
|
2105
|
+
* Runs `work` after everything asked for the same folder before it has finished. The import, the editor and the assistant each read `world.json`, change a field and write it
|
|
2106
|
+
* back; run side by side, the last one to write would take back what the others changed.
|
|
2107
|
+
*/
|
|
2108
|
+
function serialized(directory, work) {
|
|
2109
|
+
const run = (queues.get(directory) ?? Promise.resolve()).then(work, work);
|
|
2110
|
+
const tail = run.then(() => void 0, () => void 0);
|
|
2111
|
+
queues.set(directory, tail);
|
|
2112
|
+
tail.then(() => {
|
|
2113
|
+
if (queues.get(directory) === tail) queues.delete(directory);
|
|
2114
|
+
});
|
|
2115
|
+
return run;
|
|
2116
|
+
}
|
|
2117
|
+
/** Changes `world.json` in place: read, `update`, written back in one step with the indentation the file had, nothing else moving in between. @returns the document as written. */
|
|
2118
|
+
function updateWorldFile(directory, update) {
|
|
2119
|
+
return serialized(directory, async () => {
|
|
2120
|
+
const file = join(directory, WORLD_FILE_NAME);
|
|
2121
|
+
const text = await readFile(file, "utf8");
|
|
2122
|
+
const document = JSON.parse(text.replace(/^/, ""));
|
|
2123
|
+
await update(document);
|
|
2124
|
+
await atomicWrite(file, JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") || text.trim() === "" ? "\n" : ""));
|
|
2125
|
+
return document;
|
|
2126
|
+
});
|
|
2127
|
+
}
|
|
2128
|
+
//#endregion
|
|
2129
|
+
//#region src/host/import/finish.ts
|
|
2130
|
+
const STAGE = "stage";
|
|
2131
|
+
const MAX_DESCRIPTION = 500;
|
|
2132
|
+
const MAX_TAGS = 8;
|
|
2133
|
+
const MAX_TAG = 30;
|
|
2134
|
+
const FOLDERS = [
|
|
2135
|
+
{
|
|
2136
|
+
key: "characters",
|
|
2137
|
+
directory: CHARACTERS_DIR,
|
|
2138
|
+
file: CHARACTER_FILE_NAME
|
|
2139
|
+
},
|
|
2140
|
+
{
|
|
2141
|
+
key: "locations",
|
|
2142
|
+
directory: LOCATIONS_DIR,
|
|
2143
|
+
file: LOCATION_FILE_NAME
|
|
2144
|
+
},
|
|
2145
|
+
{
|
|
2146
|
+
key: "factions",
|
|
2147
|
+
directory: FACTIONS_DIR,
|
|
2148
|
+
file: FACTION_FILE_NAME
|
|
2149
|
+
},
|
|
2150
|
+
{
|
|
2151
|
+
key: "items",
|
|
2152
|
+
directory: ITEMS_DIR,
|
|
2153
|
+
file: ITEM_FILE_NAME
|
|
2154
|
+
},
|
|
2155
|
+
{
|
|
2156
|
+
key: "lore",
|
|
2157
|
+
directory: LORE_DIR,
|
|
2158
|
+
file: LORE_FILE_NAME
|
|
2159
|
+
}
|
|
2160
|
+
];
|
|
2161
|
+
/** The card's other greetings, as the other openings a player may start with: the first message and the alternates that were not chosen. */
|
|
2162
|
+
function alternateOpenings(card, chosen, player) {
|
|
2163
|
+
if (chosen.kind === "none") return [];
|
|
2164
|
+
return [{
|
|
2165
|
+
title: "First message",
|
|
2166
|
+
text: card.firstMessage,
|
|
2167
|
+
taken: chosen.kind === "first"
|
|
2168
|
+
}, ...card.alternateGreetings.map((text, index) => ({
|
|
2169
|
+
title: `Alternate ${index + 1}`,
|
|
2170
|
+
text,
|
|
2171
|
+
taken: chosen.kind === "alternate" && chosen.index === index
|
|
2172
|
+
}))].flatMap(({ title, text, taken }) => {
|
|
2173
|
+
const cleaned = taken || text.trim() === "" ? "" : openingMessage(text, card.name, player);
|
|
2174
|
+
return cleaned === "" || cleaned.length > 2e4 ? [] : [{
|
|
2175
|
+
title,
|
|
2176
|
+
text: cleaned
|
|
2177
|
+
}];
|
|
2178
|
+
}).slice(0, 30);
|
|
2179
|
+
}
|
|
2180
|
+
/** The character the card's picture shows: the one that carries the card's name, or the only one there is. */
|
|
2181
|
+
function cardCharacter(characters, cardName) {
|
|
2182
|
+
return characters.find((document) => norm(String(document["name"])) === norm(cardName)) ?? (characters.length === 1 ? characters[0] : void 0);
|
|
2183
|
+
}
|
|
2184
|
+
/** Makes the card's picture the canonical reference portrait of its character, as an image the person brought. */
|
|
2185
|
+
async function writePortrait(directory, picture, characters, cardName) {
|
|
2186
|
+
const character = cardCharacter(characters, cardName);
|
|
2187
|
+
if (character === void 0) return false;
|
|
2188
|
+
const id = String(character["id"]);
|
|
2189
|
+
const file = referenceImagePath(directory, {
|
|
2190
|
+
kind: "character",
|
|
2191
|
+
localId: id
|
|
2192
|
+
});
|
|
2193
|
+
await writeAtomically(file, picture);
|
|
2194
|
+
await writeImageFileMetadata(file, {
|
|
2195
|
+
schema: "dsh-roleplay-image/v3",
|
|
2196
|
+
purpose: "reference",
|
|
2197
|
+
origin: "uploaded",
|
|
2198
|
+
reusable: false,
|
|
2199
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2200
|
+
originalName: PICTURE_FILE,
|
|
2201
|
+
description: `${String(character["name"])}: the portrait that came with the character card.`,
|
|
2202
|
+
tags: [String(character["name"])],
|
|
2203
|
+
subjects: [{
|
|
2204
|
+
kind: "character",
|
|
2205
|
+
localId: id,
|
|
2206
|
+
name: String(character["name"])
|
|
2207
|
+
}]
|
|
2208
|
+
});
|
|
2209
|
+
return true;
|
|
2210
|
+
}
|
|
2211
|
+
/** The card's opening as the world's opening message: plain paragraphs, without the markup the card's tool read as emphasis. */
|
|
2212
|
+
function openingMessage(raw, cardName, player) {
|
|
2213
|
+
const text = cleanText(raw, cardName).replace(/<\/?[a-z][^>\n]*>/gi, "").replace(/```[a-z]*\n?|```/g, "").replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/(^|[^*])\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)/g, "$1$2").replace(/\n{3,}/g, "\n\n").trim();
|
|
2214
|
+
return withPlayer(text, player);
|
|
2215
|
+
}
|
|
2216
|
+
/** Every player marker in the strings of a value, replaced by the player's character or a plain word for the player; the value is changed in place. */
|
|
2217
|
+
function replacePlayer(value, player) {
|
|
2218
|
+
if (Array.isArray(value)) value.forEach((entry, index) => {
|
|
2219
|
+
if (typeof entry === "string") value[index] = withPlayer(entry, player);
|
|
2220
|
+
else replacePlayer(entry, player);
|
|
2221
|
+
});
|
|
2222
|
+
else if (typeof value === "object" && value !== null) {
|
|
2223
|
+
const record = value;
|
|
2224
|
+
for (const key of Object.keys(record)) {
|
|
2225
|
+
const entry = record[key];
|
|
2226
|
+
if (typeof entry === "string") record[key] = withPlayer(entry, player);
|
|
2227
|
+
else replacePlayer(entry, player);
|
|
2228
|
+
}
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
/**
|
|
2232
|
+
* Every character knows every place of the imported world and the ways between them, unless its own file already says what it knows: a card describes a
|
|
2233
|
+
* world its people live in, and without this the closed-world rules would forbid a walk to a famous street. Changes the documents in place.
|
|
2234
|
+
*/
|
|
2235
|
+
function shareThePlaces(characters, locations) {
|
|
2236
|
+
const places = locations.map((location) => String(location["id"]));
|
|
2237
|
+
const ways = [];
|
|
2238
|
+
for (const location of locations) {
|
|
2239
|
+
const from = String(location["id"]);
|
|
2240
|
+
for (const exit of Array.isArray(location["exits"]) ? location["exits"] : []) {
|
|
2241
|
+
const to = String(exit["to"]);
|
|
2242
|
+
ways.push({
|
|
2243
|
+
from,
|
|
2244
|
+
to
|
|
2245
|
+
});
|
|
2246
|
+
if (exit["one_way"] !== true) ways.push({
|
|
2247
|
+
from: to,
|
|
2248
|
+
to: from
|
|
2249
|
+
});
|
|
2250
|
+
}
|
|
2251
|
+
}
|
|
2252
|
+
for (const character of characters) {
|
|
2253
|
+
const knowledge = typeof character["knowledge"] === "object" && character["knowledge"] !== null ? character["knowledge"] : {};
|
|
2254
|
+
if (knowledge["locations"] !== void 0 || knowledge["exits"] !== void 0) continue;
|
|
2255
|
+
knowledge["locations"] = places;
|
|
2256
|
+
knowledge["exits"] = ways.filter((way, index) => ways.findIndex((other) => other.from === way.from && other.to === way.to) === index);
|
|
2257
|
+
character["knowledge"] = knowledge;
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
/** Places that contain each other in a circle are untangled by taking the parent off the one that closes it. */
|
|
2261
|
+
function breakParentCircles(locations) {
|
|
2262
|
+
const notes = [];
|
|
2263
|
+
const byId = new Map(locations.map((location) => [String(location["id"]), location]));
|
|
2264
|
+
for (const location of locations) {
|
|
2265
|
+
const seen = /* @__PURE__ */ new Set([String(location["id"])]);
|
|
2266
|
+
for (let up = location["parent"]; up !== void 0; up = byId.get(up)?.["parent"]) {
|
|
2267
|
+
if (seen.has(up)) {
|
|
2268
|
+
notes.push(`${String(location["name"])}: the places contain each other in a circle, so it is not put inside another place`);
|
|
2269
|
+
delete location["parent"];
|
|
2270
|
+
break;
|
|
2271
|
+
}
|
|
2272
|
+
seen.add(up);
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
return notes;
|
|
2276
|
+
}
|
|
2277
|
+
const WORLD_SCHEMA = {
|
|
2278
|
+
type: "object",
|
|
2279
|
+
properties: {
|
|
2280
|
+
description: {
|
|
2281
|
+
type: "string",
|
|
2282
|
+
description: `Two or three sentences, at most ${MAX_DESCRIPTION} characters.`
|
|
2283
|
+
},
|
|
2284
|
+
tags: {
|
|
2285
|
+
type: "array",
|
|
2286
|
+
items: { type: "string" },
|
|
2287
|
+
description: `At most ${MAX_TAGS} short tags.`
|
|
2288
|
+
},
|
|
2289
|
+
starting_time: {
|
|
2290
|
+
type: "string",
|
|
2291
|
+
description: "When the story begins, as an ISO 8601 date and time such as 1921-10-23T08:00:00, only when the text states the date or year; otherwise an empty string."
|
|
2292
|
+
}
|
|
2293
|
+
},
|
|
2294
|
+
required: [
|
|
2295
|
+
"description",
|
|
2296
|
+
"tags",
|
|
2297
|
+
"starting_time"
|
|
2298
|
+
],
|
|
2299
|
+
additionalProperties: false
|
|
2300
|
+
};
|
|
2301
|
+
const STARTING_TIME = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2})?)?$/;
|
|
2302
|
+
function worldJob(text, tr, card, roster, scenario, opening) {
|
|
2303
|
+
const names = (kind) => roster.filter((entity) => entity.kind === kind).slice(0, 15).map((entity) => entity.name).join("; ");
|
|
2304
|
+
return {
|
|
2305
|
+
persona: text("import/world-summary"),
|
|
2306
|
+
maxTokens: 1500,
|
|
2307
|
+
prompt: [
|
|
2308
|
+
tr("Card: {name}", { name: card.name }),
|
|
2309
|
+
...card.tags.length === 0 ? [] : [tr("Card tags: {tags}", { tags: card.tags.join(", ") })],
|
|
2310
|
+
`${tr("Characters:")} ${names("character") || tr("(none)")}`,
|
|
2311
|
+
`${tr("Places:")} ${names("place") || tr("(none)")}`,
|
|
2312
|
+
`${tr("Scenario:")}\n${scenario.slice(0, 1200) || tr("(none)")}`,
|
|
2313
|
+
`${tr("Opening:")}\n${opening.slice(0, 1200) || tr("(none)")}`,
|
|
2314
|
+
`${tr("Description:")}\n${cleanText(card.description, card.name).slice(0, 1200) || tr("(none)")}`,
|
|
2315
|
+
`${tr("Creator's notes:")}\n${cleanText(card.creatorNotes, card.name).slice(0, 600) || tr("(none)")}`
|
|
2316
|
+
].join("\n\n"),
|
|
2317
|
+
result: WORLD_SCHEMA,
|
|
2318
|
+
check: (value) => {
|
|
2319
|
+
if (value.description.trim() === "" || value.description.length > MAX_DESCRIPTION) return `the description must be written and at most ${MAX_DESCRIPTION} characters`;
|
|
2320
|
+
if (value.tags.length > MAX_TAGS || value.tags.some((tag) => tag.trim() === "" || tag.length > MAX_TAG)) return `give at most ${MAX_TAGS} tags of at most ${MAX_TAG} characters`;
|
|
2321
|
+
if ((value.starting_time ?? "").trim() !== "" && (!STARTING_TIME.test(value.starting_time.trim()) || Number.isNaN(Date.parse(value.starting_time.trim())))) return "starting_time must be an ISO 8601 date and time such as 1921-10-23T08:00:00, or empty";
|
|
2322
|
+
}
|
|
2323
|
+
};
|
|
2324
|
+
}
|
|
2325
|
+
/** The description and tags of the world: asked of one call, and from the card's own fields when that fails. */
|
|
2326
|
+
async function describeWorld(ctx, card, roster, items, opening) {
|
|
2327
|
+
const scenario = items.filter((item) => item.id.startsWith("field:scenario")).map((item) => item.text).join("\n\n");
|
|
2328
|
+
try {
|
|
2329
|
+
const answer = await ctx.run(worldJob(ctx.text, trOf(ctx), card, roster, scenario, opening));
|
|
2330
|
+
return {
|
|
2331
|
+
description: answer.description.trim(),
|
|
2332
|
+
tags: [...new Set(answer.tags.map((tag) => tag.trim()))],
|
|
2333
|
+
...(answer.starting_time ?? "").trim() === "" ? {} : { startingTime: answer.starting_time.trim() }
|
|
2334
|
+
};
|
|
2335
|
+
} catch (error) {
|
|
2336
|
+
return {
|
|
2337
|
+
description: (scenario || cleanText(card.description, card.name)).slice(0, MAX_DESCRIPTION).trim(),
|
|
2338
|
+
tags: card.tags.filter((tag) => tag.trim() !== "" && tag.length <= MAX_TAG).slice(0, MAX_TAGS),
|
|
2339
|
+
note: `the description of the world was taken from the card as it is: ${error instanceof Error ? error.message : String(error)}`
|
|
2340
|
+
};
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
async function hasEntities(world) {
|
|
2344
|
+
for (const { directory } of FOLDERS) try {
|
|
2345
|
+
if ((await readdir(join(world, directory))).some((name) => !name.startsWith("."))) return true;
|
|
2346
|
+
} catch (error) {
|
|
2347
|
+
if (error.code !== "ENOENT") throw error;
|
|
2348
|
+
}
|
|
2349
|
+
return false;
|
|
2350
|
+
}
|
|
2351
|
+
const writeAtomically = (file, text) => atomicWrite(file, text, { createDirectory: true });
|
|
2352
|
+
/**
|
|
2353
|
+
* Writes what was extracted into the world, all at once. The documents are first written to a staging folder and read back as the world will
|
|
2354
|
+
* read them when a session starts; only when every part of the world is valid are they moved in. The world's own file gets its description, tags, opening and cover.
|
|
2355
|
+
*/
|
|
2356
|
+
async function finishImport(ctx, input) {
|
|
2357
|
+
const { directory, card, choices, roster, items, classified, extracted } = input;
|
|
2358
|
+
if (await hasEntities(directory)) return {
|
|
2359
|
+
ok: false,
|
|
2360
|
+
problems: ["the world already has characters, places, factions, things or lore: an import only fills an empty world"]
|
|
2361
|
+
};
|
|
2362
|
+
const playing = extracted.characters.find((document) => document["role"] === "playable");
|
|
2363
|
+
const playerName = playing === void 0 ? void 0 : String(playing["name"]);
|
|
2364
|
+
for (const key of [
|
|
2365
|
+
"characters",
|
|
2366
|
+
"locations",
|
|
2367
|
+
"factions",
|
|
2368
|
+
"items",
|
|
2369
|
+
"lore",
|
|
2370
|
+
"commands",
|
|
2371
|
+
"triggers",
|
|
2372
|
+
"variables"
|
|
2373
|
+
]) replacePlayer(extracted[key], playerName);
|
|
2374
|
+
const notes = [
|
|
2375
|
+
...input.notes,
|
|
2376
|
+
...extracted.notes,
|
|
2377
|
+
...breakParentCircles(extracted.locations)
|
|
2378
|
+
];
|
|
2379
|
+
shareThePlaces(extracted.characters, extracted.locations);
|
|
2380
|
+
const stage = join(directory, IMPORT_FOLDER, STAGE);
|
|
2381
|
+
await rm(stage, {
|
|
2382
|
+
recursive: true,
|
|
2383
|
+
force: true
|
|
2384
|
+
});
|
|
2385
|
+
const mend = () => {
|
|
2386
|
+
const view = {
|
|
2387
|
+
...extracted,
|
|
2388
|
+
notes
|
|
2389
|
+
};
|
|
2390
|
+
pruneLoreSubjects(view);
|
|
2391
|
+
pruneMembers(view);
|
|
2392
|
+
pruneLinks(view);
|
|
2393
|
+
pruneKnowledge(view);
|
|
2394
|
+
pruneRelationships(view);
|
|
2395
|
+
};
|
|
2396
|
+
mend();
|
|
2397
|
+
try {
|
|
2398
|
+
if (extracted.variables.length > 0) await writeAtomically(join(stage, VARIABLES_FILE_NAME), `${JSON.stringify(extracted.variables, null, 2)}\n`);
|
|
2399
|
+
if (extracted.commands.length > 0) await writeAtomically(join(stage, COMMANDS_FILE_NAME), `${JSON.stringify({ commands: extracted.commands }, null, 2)}\n`);
|
|
2400
|
+
if (extracted.triggers.length > 0) await writeAtomically(join(stage, TRIGGERS_FILE_NAME), `${JSON.stringify(extracted.triggers, null, 2)}\n`);
|
|
2401
|
+
for (const { key, directory: folder, file } of FOLDERS) for (const document of extracted[key]) await writeAtomically(join(stage, folder, String(document["id"]), file), `${JSON.stringify(document, null, 2)}\n`);
|
|
2402
|
+
for (const { id, text } of extracted.prompts) {
|
|
2403
|
+
const problem = promptProblem("en", id, text);
|
|
2404
|
+
if (problem !== void 0) return {
|
|
2405
|
+
ok: false,
|
|
2406
|
+
problems: [`prompt ${id}: ${problem}`]
|
|
2407
|
+
};
|
|
2408
|
+
}
|
|
2409
|
+
if (extracted.variables.length > 0) await rename(join(stage, VARIABLES_FILE_NAME), join(directory, VARIABLES_FILE_NAME));
|
|
2410
|
+
if (extracted.commands.length > 0) await rename(join(stage, COMMANDS_FILE_NAME), join(directory, COMMANDS_FILE_NAME));
|
|
2411
|
+
if (extracted.triggers.length > 0) await rename(join(stage, TRIGGERS_FILE_NAME), join(directory, TRIGGERS_FILE_NAME));
|
|
2412
|
+
for (const { directory: folder } of FOLDERS) {
|
|
2413
|
+
const from = join(stage, folder);
|
|
2414
|
+
if (await stat(from).then(() => true, () => false)) await rename(from, join(directory, folder));
|
|
2415
|
+
}
|
|
2416
|
+
} finally {
|
|
2417
|
+
await rm(stage, {
|
|
2418
|
+
recursive: true,
|
|
2419
|
+
force: true
|
|
2420
|
+
});
|
|
2421
|
+
}
|
|
2422
|
+
const check = await checkWorld({
|
|
2423
|
+
directory,
|
|
2424
|
+
summary: { name: choices.name }
|
|
2425
|
+
});
|
|
2426
|
+
if (!check.ok) notes.push(`the world was written as a draft: it would not start yet (${check.problems.length + check.more} problem(s) in ${check.summary ?? "the world"})`);
|
|
2427
|
+
const player = extracted.characters.find((document) => document["role"] === "playable");
|
|
2428
|
+
for (const { id, text } of extracted.prompts) for (const language of shippedLanguages()) await writeAtomically(join(directory, PROMPTS_FOLDER, language, `${id}.md`), `${withPlayer(text, player === void 0 ? void 0 : String(player["name"]))}\n`);
|
|
2429
|
+
const opening = openingText(card, choices.opening);
|
|
2430
|
+
const described = await describeWorld(ctx, card, roster, items, opening ?? "");
|
|
2431
|
+
if (described.note !== void 0) notes.push(described.note);
|
|
2432
|
+
described.description = withPlayer(described.description, player === void 0 ? void 0 : String(player["name"]));
|
|
2433
|
+
let cover = false;
|
|
2434
|
+
if (input.picture !== void 0) {
|
|
2435
|
+
await writeAtomically(join(directory, "media", "files", "cover.png"), input.picture);
|
|
2436
|
+
await writeAtomically(join(directory, "media", "manifest.jsonl"), `${JSON.stringify({
|
|
2437
|
+
id: "cover",
|
|
2438
|
+
file: "media/files/cover.png"
|
|
2439
|
+
})}\n`);
|
|
2440
|
+
cover = true;
|
|
2441
|
+
}
|
|
2442
|
+
const alternates = alternateOpenings(card, choices.opening, player === void 0 ? void 0 : String(player["name"]));
|
|
2443
|
+
await updateWorldFile(directory, (world) => {
|
|
2444
|
+
world["description"] = described.description;
|
|
2445
|
+
if (described.startingTime !== void 0 && world["starting_time"] === void 0) world["starting_time"] = described.startingTime;
|
|
2446
|
+
world["metadata"] = {
|
|
2447
|
+
...typeof world["metadata"] === "object" && world["metadata"] !== null ? world["metadata"] : {},
|
|
2448
|
+
tags: described.tags
|
|
2449
|
+
};
|
|
2450
|
+
if (opening !== void 0) world["opening_message"] = openingMessage(opening, card.name, player === void 0 ? void 0 : String(player["name"]));
|
|
2451
|
+
if (alternates.length > 0) world["alternate_openings"] = alternates;
|
|
2452
|
+
if (card.creator.trim() !== "" && world["author"] === void 0) world["author"] = { name: card.creator.trim() };
|
|
2453
|
+
if (cover) world["cover_media_id"] = "cover";
|
|
2454
|
+
});
|
|
2455
|
+
let portrait = false;
|
|
2456
|
+
if (input.picture !== void 0) try {
|
|
2457
|
+
portrait = await writePortrait(directory, input.picture, extracted.characters, card.name);
|
|
2458
|
+
} catch (error) {
|
|
2459
|
+
notes.push(`the card's picture could not be used as a portrait: ${error instanceof Error ? error.message : String(error)}`);
|
|
2460
|
+
}
|
|
2461
|
+
const taken = (role) => items.filter((item) => {
|
|
2462
|
+
const classification = classified[item.id];
|
|
2463
|
+
return classification !== void 0 && isLeftOut(classification) && classification.roles[0] === role;
|
|
2464
|
+
}).length;
|
|
2465
|
+
const report = {
|
|
2466
|
+
prompts: extracted.prompts.map((entry) => entry.id),
|
|
2467
|
+
variables: extracted.variables.length,
|
|
2468
|
+
counts: {
|
|
2469
|
+
characters: extracted.characters.length,
|
|
2470
|
+
places: extracted.locations.length,
|
|
2471
|
+
factions: extracted.factions.length,
|
|
2472
|
+
things: extracted.items.length,
|
|
2473
|
+
lore: extracted.lore.length
|
|
2474
|
+
},
|
|
2475
|
+
hasPlayableCharacter: player !== void 0,
|
|
2476
|
+
opening: opening === void 0 ? "none" : "imported",
|
|
2477
|
+
alternateOpenings: alternates.length,
|
|
2478
|
+
cover,
|
|
2479
|
+
portrait,
|
|
2480
|
+
leftOut: {
|
|
2481
|
+
instructions: taken("instruction"),
|
|
2482
|
+
templates: taken("template"),
|
|
2483
|
+
irrelevant: taken("irrelevant"),
|
|
2484
|
+
scripts: card.ignored.scripts
|
|
2485
|
+
},
|
|
2486
|
+
pictures: input.pictures ?? {
|
|
2487
|
+
found: 0,
|
|
2488
|
+
added: 0
|
|
2489
|
+
},
|
|
2490
|
+
notes
|
|
2491
|
+
};
|
|
2492
|
+
await writeAtomically(join(directory, IMPORT_FOLDER, "report.json"), JSON.stringify(report, null, 2));
|
|
2493
|
+
return {
|
|
2494
|
+
ok: true,
|
|
2495
|
+
report,
|
|
2496
|
+
...check.ok ? {} : { draft: check }
|
|
2497
|
+
};
|
|
2498
|
+
}
|
|
2499
|
+
//#endregion
|
|
2500
|
+
//#region src/host/import/pictures.ts
|
|
2501
|
+
/** The address is not one a picture may be fetched from: it names this machine or a private network. */
|
|
2502
|
+
var BlockedAddressError = class extends Error {};
|
|
2503
|
+
const MAX_BYTES = 20971520;
|
|
2504
|
+
const MIN_BYTES = 1024;
|
|
2505
|
+
const MAX_REDIRECTS = 4;
|
|
2506
|
+
const TIMEOUT_MS = 3e4;
|
|
2507
|
+
const CONCURRENCY = 8;
|
|
2508
|
+
const NON_IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
2509
|
+
"js",
|
|
2510
|
+
"mjs",
|
|
2511
|
+
"cjs",
|
|
2512
|
+
"css",
|
|
2513
|
+
"html",
|
|
2514
|
+
"htm",
|
|
2515
|
+
"json",
|
|
2516
|
+
"xml",
|
|
2517
|
+
"txt",
|
|
2518
|
+
"md",
|
|
2519
|
+
"map",
|
|
2520
|
+
"wasm",
|
|
2521
|
+
"php",
|
|
2522
|
+
"py",
|
|
2523
|
+
"woff",
|
|
2524
|
+
"woff2",
|
|
2525
|
+
"ttf",
|
|
2526
|
+
"otf",
|
|
2527
|
+
"eot",
|
|
2528
|
+
"mp3",
|
|
2529
|
+
"wav",
|
|
2530
|
+
"ogg",
|
|
2531
|
+
"flac",
|
|
2532
|
+
"m4a",
|
|
2533
|
+
"mp4",
|
|
2534
|
+
"webm",
|
|
2535
|
+
"mkv",
|
|
2536
|
+
"mov",
|
|
2537
|
+
"avi",
|
|
2538
|
+
"zip",
|
|
2539
|
+
"rar",
|
|
2540
|
+
"gz",
|
|
2541
|
+
"7z",
|
|
2542
|
+
"pdf",
|
|
2543
|
+
"doc",
|
|
2544
|
+
"docx"
|
|
2545
|
+
]);
|
|
2546
|
+
const blocked = new BlockList();
|
|
2547
|
+
for (const [network, prefix] of [
|
|
2548
|
+
["0.0.0.0", 8],
|
|
2549
|
+
["10.0.0.0", 8],
|
|
2550
|
+
["100.64.0.0", 10],
|
|
2551
|
+
["127.0.0.0", 8],
|
|
2552
|
+
["169.254.0.0", 16],
|
|
2553
|
+
["172.16.0.0", 12],
|
|
2554
|
+
["192.0.0.0", 24],
|
|
2555
|
+
["192.0.2.0", 24],
|
|
2556
|
+
["192.88.99.0", 24],
|
|
2557
|
+
["192.168.0.0", 16],
|
|
2558
|
+
["198.18.0.0", 15],
|
|
2559
|
+
["198.51.100.0", 24],
|
|
2560
|
+
["203.0.113.0", 24],
|
|
2561
|
+
["224.0.0.0", 4],
|
|
2562
|
+
["240.0.0.0", 4]
|
|
2563
|
+
]) blocked.addSubnet(network, prefix, "ipv4");
|
|
2564
|
+
for (const [network, prefix] of [
|
|
2565
|
+
["::", 128],
|
|
2566
|
+
["::1", 128],
|
|
2567
|
+
["64:ff9b::", 96],
|
|
2568
|
+
["100::", 64],
|
|
2569
|
+
["2001::", 32],
|
|
2570
|
+
["2001:db8::", 32],
|
|
2571
|
+
["2002::", 16],
|
|
2572
|
+
["fc00::", 7],
|
|
2573
|
+
["fe80::", 10],
|
|
2574
|
+
["ff00::", 8]
|
|
2575
|
+
]) blocked.addSubnet(network, prefix, "ipv6");
|
|
2576
|
+
/** Whether an address may be connected to: only public unicast addresses may. */
|
|
2577
|
+
function isPublicAddress(address) {
|
|
2578
|
+
const family = isIP(address);
|
|
2579
|
+
if (family === 0) return false;
|
|
2580
|
+
if (family === 4) return !blocked.check(address, "ipv4");
|
|
2581
|
+
const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(new URL(`http://[${address}]/`).hostname.replace(/^\[|\]$/g, ""));
|
|
2582
|
+
if (mapped !== null) {
|
|
2583
|
+
const high = Number.parseInt(mapped[1], 16);
|
|
2584
|
+
const low = Number.parseInt(mapped[2], 16);
|
|
2585
|
+
return isPublicAddress(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`);
|
|
2586
|
+
}
|
|
2587
|
+
return !blocked.check(address, "ipv6");
|
|
2588
|
+
}
|
|
2589
|
+
/** The address a picture may be asked for, or why not: web only, standard ports, no credentials, no private literal address. */
|
|
2590
|
+
function vetUrl(raw) {
|
|
2591
|
+
let url;
|
|
2592
|
+
try {
|
|
2593
|
+
url = new URL(raw);
|
|
2594
|
+
} catch {
|
|
2595
|
+
return "not an address";
|
|
2596
|
+
}
|
|
2597
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return "not a web address";
|
|
2598
|
+
if (url.username !== "" || url.password !== "") return "has credentials";
|
|
2599
|
+
if (url.port !== "" && url.port !== "80" && url.port !== "443") return "uses an unusual port";
|
|
2600
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
2601
|
+
if (isIP(host) !== 0 && !isPublicAddress(host)) return "is a private address";
|
|
2602
|
+
return url;
|
|
2603
|
+
}
|
|
2604
|
+
/** The addresses worth asking about: a picture file name, or a name with no file type at all. */
|
|
2605
|
+
function candidateUrls(urls) {
|
|
2606
|
+
const candidates = [];
|
|
2607
|
+
const skipped = [];
|
|
2608
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2609
|
+
for (const raw of urls) {
|
|
2610
|
+
const url = vetUrl(raw);
|
|
2611
|
+
if (typeof url === "string") {
|
|
2612
|
+
skipped.push({
|
|
2613
|
+
url: raw,
|
|
2614
|
+
reason: url
|
|
2615
|
+
});
|
|
2616
|
+
continue;
|
|
2617
|
+
}
|
|
2618
|
+
url.hash = "";
|
|
2619
|
+
const key = url.href;
|
|
2620
|
+
if (seen.has(key)) continue;
|
|
2621
|
+
seen.add(key);
|
|
2622
|
+
const extension = /\.([a-z0-9]{1,5})$/i.exec(url.pathname)?.[1]?.toLowerCase();
|
|
2623
|
+
if (extension !== void 0 && MEDIA_TYPES[`.${extension}`] === void 0) skipped.push({
|
|
2624
|
+
url: raw,
|
|
2625
|
+
reason: NON_IMAGE_EXTENSIONS.has(extension) ? "not an image" : "format not supported"
|
|
2626
|
+
});
|
|
2627
|
+
else candidates.push(key);
|
|
2628
|
+
}
|
|
2629
|
+
return {
|
|
2630
|
+
candidates,
|
|
2631
|
+
skipped
|
|
2632
|
+
};
|
|
2633
|
+
}
|
|
2634
|
+
/** Looks the name up and refuses it when any answer is not public, at the moment of connecting, so a name cannot change between the check and the use. */
|
|
2635
|
+
const guardedLookup = (hostname, options, callback) => {
|
|
2636
|
+
lookup(hostname, {
|
|
2637
|
+
...options,
|
|
2638
|
+
all: true
|
|
2639
|
+
}, (error, addresses) => {
|
|
2640
|
+
if (error !== null) {
|
|
2641
|
+
callback(error, "", 0);
|
|
2642
|
+
return;
|
|
2643
|
+
}
|
|
2644
|
+
if (addresses.find((entry) => !isPublicAddress(entry.address)) !== void 0 || addresses.length === 0) {
|
|
2645
|
+
callback(new BlockedAddressError(`${hostname} is not a public address`), "", 0);
|
|
2646
|
+
return;
|
|
2647
|
+
}
|
|
2648
|
+
if (options.all === true) callback(null, addresses);
|
|
2649
|
+
else callback(null, addresses[0].address, addresses[0].family);
|
|
2650
|
+
});
|
|
2651
|
+
};
|
|
2652
|
+
async function readBody(response) {
|
|
2653
|
+
const chunks = [];
|
|
2654
|
+
let size = 0;
|
|
2655
|
+
for await (const chunk of response) {
|
|
2656
|
+
size += chunk.length;
|
|
2657
|
+
if (size > MAX_BYTES) {
|
|
2658
|
+
response.destroy();
|
|
2659
|
+
throw new Error("too large");
|
|
2660
|
+
}
|
|
2661
|
+
chunks.push(chunk);
|
|
2662
|
+
}
|
|
2663
|
+
return Buffer.concat(chunks);
|
|
2664
|
+
}
|
|
2665
|
+
/** One request, never following a redirect, with the connection itself checked against private networks. */
|
|
2666
|
+
const requestOnce = (url, method, signal) => new Promise((resolveReply, reject) => {
|
|
2667
|
+
const request$2 = (url.protocol === "https:" ? request$1 : request)(url, {
|
|
2668
|
+
method,
|
|
2669
|
+
lookup: guardedLookup,
|
|
2670
|
+
signal,
|
|
2671
|
+
timeout: TIMEOUT_MS,
|
|
2672
|
+
agent: false,
|
|
2673
|
+
headers: {
|
|
2674
|
+
"user-agent": "Mozilla/5.0 (compatible; dsh-roleplay-import)",
|
|
2675
|
+
accept: "image/*,*/*;q=0.5",
|
|
2676
|
+
"accept-encoding": "identity"
|
|
2677
|
+
}
|
|
2678
|
+
}, (response) => {
|
|
2679
|
+
const status = response.statusCode ?? 0;
|
|
2680
|
+
const type = String(response.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase();
|
|
2681
|
+
const location = typeof response.headers.location === "string" ? response.headers.location : void 0;
|
|
2682
|
+
const length = Number(response.headers["content-length"] ?? 0);
|
|
2683
|
+
if (method === "HEAD" || status < 200 || status >= 300 || location !== void 0 && status >= 300) {
|
|
2684
|
+
response.destroy();
|
|
2685
|
+
resolveReply({
|
|
2686
|
+
status,
|
|
2687
|
+
type,
|
|
2688
|
+
location,
|
|
2689
|
+
body: Buffer.alloc(0)
|
|
2690
|
+
});
|
|
2691
|
+
return;
|
|
2692
|
+
}
|
|
2693
|
+
if (length > MAX_BYTES) {
|
|
2694
|
+
response.destroy();
|
|
2695
|
+
reject(/* @__PURE__ */ new Error("too large"));
|
|
2696
|
+
return;
|
|
2697
|
+
}
|
|
2698
|
+
readBody(response).then((body) => {
|
|
2699
|
+
resolveReply({
|
|
2700
|
+
status,
|
|
2701
|
+
type,
|
|
2702
|
+
location,
|
|
2703
|
+
body
|
|
2704
|
+
});
|
|
2705
|
+
}, reject);
|
|
2706
|
+
});
|
|
2707
|
+
request$2.on("timeout", () => {
|
|
2708
|
+
request$2.destroy(/* @__PURE__ */ new Error("timed out"));
|
|
2709
|
+
});
|
|
2710
|
+
request$2.on("error", reject);
|
|
2711
|
+
request$2.end();
|
|
2712
|
+
});
|
|
2713
|
+
/** Asks for the address, following up to a few redirects, each vetted like the first address. */
|
|
2714
|
+
async function follow(fetcher, start, method, signal) {
|
|
2715
|
+
let url = start;
|
|
2716
|
+
for (let hop = 0;; hop += 1) {
|
|
2717
|
+
const reply = await fetcher(url, method, signal);
|
|
2718
|
+
if (reply.status < 300 || reply.status >= 400 || reply.location === void 0) return reply;
|
|
2719
|
+
if (hop >= MAX_REDIRECTS) throw new Error("too many redirects");
|
|
2720
|
+
const next = vetUrl(new URL(reply.location, url).href);
|
|
2721
|
+
if (typeof next === "string") throw new BlockedAddressError(`a redirect ${next}`);
|
|
2722
|
+
url = next;
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
const GENERIC_TYPES = /* @__PURE__ */ new Set([
|
|
2726
|
+
"",
|
|
2727
|
+
"application/octet-stream",
|
|
2728
|
+
"binary/octet-stream",
|
|
2729
|
+
"application/binary",
|
|
2730
|
+
"application/x-binary"
|
|
2731
|
+
]);
|
|
2732
|
+
const SUPPORTED_TYPES = new Set(Object.values(MEDIA_TYPES));
|
|
2733
|
+
/** What a HEAD request says about an address: not a picture, or worth fetching (a picture, or an answer that settles nothing because the service does not do HEAD). */
|
|
2734
|
+
async function worthFetching(fetcher, url, signal) {
|
|
2735
|
+
let reply;
|
|
2736
|
+
try {
|
|
2737
|
+
reply = await follow(fetcher, url, "HEAD", signal);
|
|
2738
|
+
} catch (error) {
|
|
2739
|
+
return error instanceof BlockedAddressError ? error.message : void 0;
|
|
2740
|
+
}
|
|
2741
|
+
if (reply.status === 404 || reply.status === 410) return "gone";
|
|
2742
|
+
if (reply.status < 200 || reply.status >= 300) return void 0;
|
|
2743
|
+
if (reply.type.startsWith("image/")) return SUPPORTED_TYPES.has(reply.type) ? void 0 : "format not supported";
|
|
2744
|
+
return GENERIC_TYPES.has(reply.type) ? void 0 : `not an image (${reply.type})`;
|
|
2745
|
+
}
|
|
2746
|
+
function fileNameOf(url) {
|
|
2747
|
+
const last = url.pathname.split("/").pop() ?? "";
|
|
2748
|
+
try {
|
|
2749
|
+
return decodeURIComponent(last) || "image";
|
|
2750
|
+
} catch {
|
|
2751
|
+
return last || "image";
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2754
|
+
/**
|
|
2755
|
+
* Fetches the pictures a card points to into the world's image library, as if the person had added them. Each address is vetted, asked about
|
|
2756
|
+
* with HEAD, and only then downloaded; what is kept is decided by the first bytes of the file, never by its name or declared type.
|
|
2757
|
+
*/
|
|
2758
|
+
async function fetchPictures(world, urls, deps = {}) {
|
|
2759
|
+
const fetcher = deps.fetcher ?? requestOnce;
|
|
2760
|
+
const { candidates, skipped: refused } = candidateUrls(urls);
|
|
2761
|
+
const skipped = [...refused];
|
|
2762
|
+
const added = [];
|
|
2763
|
+
const hashes = await libraryHashes(world);
|
|
2764
|
+
await mapLimit(candidates, deps.concurrency ?? CONCURRENCY, async (address) => {
|
|
2765
|
+
const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS * 2), ...deps.signal === void 0 ? [] : [deps.signal]]);
|
|
2766
|
+
const url = new URL(address);
|
|
2767
|
+
try {
|
|
2768
|
+
const refusal = await worthFetching(fetcher, url, signal);
|
|
2769
|
+
if (refusal !== void 0) {
|
|
2770
|
+
skipped.push({
|
|
2771
|
+
url: address,
|
|
2772
|
+
reason: refusal
|
|
2773
|
+
});
|
|
2774
|
+
return;
|
|
2775
|
+
}
|
|
2776
|
+
const reply = await follow(fetcher, url, "GET", signal);
|
|
2777
|
+
if (reply.status < 200 || reply.status >= 300) {
|
|
2778
|
+
skipped.push({
|
|
2779
|
+
url: address,
|
|
2780
|
+
reason: `answered ${reply.status}`
|
|
2781
|
+
});
|
|
2782
|
+
return;
|
|
2783
|
+
}
|
|
2784
|
+
if (imageExtensionOf(reply.body) === void 0) {
|
|
2785
|
+
skipped.push({
|
|
2786
|
+
url: address,
|
|
2787
|
+
reason: "not an image"
|
|
2788
|
+
});
|
|
2789
|
+
return;
|
|
2790
|
+
}
|
|
2791
|
+
if (reply.body.length < MIN_BYTES) {
|
|
2792
|
+
skipped.push({
|
|
2793
|
+
url: address,
|
|
2794
|
+
reason: "too small"
|
|
2795
|
+
});
|
|
2796
|
+
return;
|
|
2797
|
+
}
|
|
2798
|
+
const { path, added: isNew } = await addToLibraryOnce(world, reply.body, fileNameOf(url), hashes);
|
|
2799
|
+
if (!isNew) {
|
|
2800
|
+
skipped.push({
|
|
2801
|
+
url: address,
|
|
2802
|
+
reason: "a copy of another picture",
|
|
2803
|
+
of: path
|
|
2804
|
+
});
|
|
2805
|
+
return;
|
|
2806
|
+
}
|
|
2807
|
+
added.push({
|
|
2808
|
+
url: address,
|
|
2809
|
+
path
|
|
2810
|
+
});
|
|
2811
|
+
} catch (error) {
|
|
2812
|
+
skipped.push({
|
|
2813
|
+
url: address,
|
|
2814
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
2815
|
+
});
|
|
2816
|
+
}
|
|
2817
|
+
});
|
|
2818
|
+
return {
|
|
2819
|
+
found: candidates.length,
|
|
2820
|
+
added,
|
|
2821
|
+
skipped
|
|
2822
|
+
};
|
|
2823
|
+
}
|
|
2824
|
+
/** The key an address is known by: the way `candidateUrls` reads it, without a fragment. */
|
|
2825
|
+
function addressKey(raw) {
|
|
2826
|
+
try {
|
|
2827
|
+
const url = new URL(raw);
|
|
2828
|
+
url.hash = "";
|
|
2829
|
+
return url.href;
|
|
2830
|
+
} catch {
|
|
2831
|
+
return raw;
|
|
2832
|
+
}
|
|
2833
|
+
}
|
|
2834
|
+
const FINAL = [
|
|
2835
|
+
/^not an? /,
|
|
2836
|
+
/^format not supported/,
|
|
2837
|
+
/^gone$/,
|
|
2838
|
+
/^too small$/,
|
|
2839
|
+
/^too large$/,
|
|
2840
|
+
/^a copy of /,
|
|
2841
|
+
/^has credentials/,
|
|
2842
|
+
/^uses an unusual port/,
|
|
2843
|
+
/^is a private address/,
|
|
2844
|
+
/^a redirect /,
|
|
2845
|
+
/is not a public address$/,
|
|
2846
|
+
/^answered (4(?!08|29)\d\d)$/
|
|
2847
|
+
];
|
|
2848
|
+
/** Whether asking again could give another answer: a picture that is not one, is gone or may not be fetched stays settled; a timeout, a server error or a refusal to wait does not. */
|
|
2849
|
+
const worthAskingAgain = (reason) => !FINAL.some((pattern) => pattern.test(reason));
|
|
2850
|
+
/**
|
|
2851
|
+
* The addresses of a newer card to ask for: those the earlier card did not have, and those it had that were not settled (the record says a request failed). With no record
|
|
2852
|
+
* of that fetch every address of the earlier card counts as settled, so what the person removed from the library is not brought back.
|
|
2853
|
+
*/
|
|
2854
|
+
function addressesToFetch(earlier, later, record) {
|
|
2855
|
+
const settled = new Set(earlier.map(addressKey));
|
|
2856
|
+
if (record !== void 0) {
|
|
2857
|
+
const unsettled = new Set(record.skipped.filter((entry) => worthAskingAgain(entry.reason)).map((entry) => addressKey(entry.url)));
|
|
2858
|
+
const fetched = new Set(record.added.map((entry) => addressKey(entry.url)));
|
|
2859
|
+
for (const key of [...settled]) if (unsettled.has(key) && !fetched.has(key)) settled.delete(key);
|
|
2860
|
+
}
|
|
2861
|
+
return later.filter((url) => !settled.has(addressKey(url)));
|
|
2862
|
+
}
|
|
2863
|
+
/** The record after a second fetch: what was added stays, an address asked again takes its new answer. */
|
|
2864
|
+
function mergeReports(earlier, later, found) {
|
|
2865
|
+
const asked = new Set([...later.added.map((entry) => entry.url), ...later.skipped.map((entry) => entry.url)].map(addressKey));
|
|
2866
|
+
return {
|
|
2867
|
+
found,
|
|
2868
|
+
added: [...earlier?.added ?? [], ...later.added],
|
|
2869
|
+
skipped: [...(earlier?.skipped ?? []).filter((entry) => !asked.has(addressKey(entry.url))), ...later.skipped]
|
|
2870
|
+
};
|
|
2871
|
+
}
|
|
2872
|
+
//#endregion
|
|
2873
|
+
//#region src/host/catalogue/errors.ts
|
|
2874
|
+
var CatalogueError = class extends Error {
|
|
2875
|
+
failure;
|
|
2876
|
+
detail;
|
|
2877
|
+
constructor(message, failure, detail) {
|
|
2878
|
+
super(message);
|
|
2879
|
+
this.failure = failure;
|
|
2880
|
+
this.detail = detail;
|
|
2881
|
+
}
|
|
2882
|
+
};
|
|
2883
|
+
//#endregion
|
|
2884
|
+
//#region src/host/catalogue/origin.ts
|
|
2885
|
+
const ORIGIN_FILE = ".catalogue.json";
|
|
2886
|
+
const MAX_LISTED_CHANGES = 12;
|
|
2887
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2888
|
+
/** The origin recorded in a world's folder, or nothing when it has none. @throws {CatalogueError} when the record is damaged. */
|
|
2889
|
+
async function readOrigin(directory) {
|
|
2890
|
+
let text;
|
|
2891
|
+
try {
|
|
2892
|
+
text = await readFile(join(directory, ORIGIN_FILE), "utf8");
|
|
2893
|
+
} catch (error) {
|
|
2894
|
+
if (error.code === "ENOENT") return void 0;
|
|
2895
|
+
throw error;
|
|
2896
|
+
}
|
|
2897
|
+
const damaged = () => new CatalogueError(`${ORIGIN_FILE} in ${directory} is damaged`, "invalid");
|
|
2898
|
+
let value;
|
|
2899
|
+
try {
|
|
2900
|
+
value = JSON.parse(text);
|
|
2901
|
+
} catch {
|
|
2902
|
+
throw damaged();
|
|
2903
|
+
}
|
|
2904
|
+
if (!isRecord(value)) throw damaged();
|
|
2905
|
+
const { kind, root, resourceId, versionId, version, files } = value;
|
|
2906
|
+
if (kind !== "release" && kind !== "card" || typeof root !== "string" || typeof resourceId !== "string" || typeof versionId !== "string" || typeof version !== "string") throw damaged();
|
|
2907
|
+
if (kind === "card") return {
|
|
2908
|
+
kind,
|
|
2909
|
+
root,
|
|
2910
|
+
resourceId,
|
|
2911
|
+
versionId,
|
|
2912
|
+
version
|
|
2913
|
+
};
|
|
2914
|
+
if (!isRecord(files) || !Object.values(files).every((hash) => typeof hash === "string")) throw damaged();
|
|
2915
|
+
return {
|
|
2916
|
+
kind,
|
|
2917
|
+
root,
|
|
2918
|
+
resourceId,
|
|
2919
|
+
versionId,
|
|
2920
|
+
version,
|
|
2921
|
+
files
|
|
2922
|
+
};
|
|
2923
|
+
}
|
|
2924
|
+
async function writeOrigin(directory, origin) {
|
|
2925
|
+
const file = join(directory, ORIGIN_FILE);
|
|
2926
|
+
await atomicWriteJson(file, origin, { indent: 2 });
|
|
2927
|
+
}
|
|
2928
|
+
/** SHA-256 of every file in a world folder; entries whose names start with a dot (this record, the trash, import state) are not the world's own. */
|
|
2929
|
+
async function hashWorld(directory, skip = () => false) {
|
|
2930
|
+
const hashes = {};
|
|
2931
|
+
const walk = async (relative) => {
|
|
2932
|
+
for (const entry of await readdir(join(directory, relative), { withFileTypes: true })) {
|
|
2933
|
+
if (relative === "" && entry.name.startsWith(".")) continue;
|
|
2934
|
+
const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
|
|
2935
|
+
if (entry.isDirectory()) await walk(path);
|
|
2936
|
+
else if (entry.isFile() && !skip(path)) hashes[path] = createHash("sha256").update(await readFile(join(directory, path))).digest("hex");
|
|
2937
|
+
}
|
|
2938
|
+
};
|
|
2939
|
+
await walk("");
|
|
2940
|
+
return hashes;
|
|
2941
|
+
}
|
|
2942
|
+
function compare(recorded, current) {
|
|
2943
|
+
return {
|
|
2944
|
+
changed: Object.keys(recorded).filter((path) => current[path] !== void 0 && current[path] !== recorded[path]),
|
|
2945
|
+
added: Object.keys(current).filter((path) => recorded[path] === void 0),
|
|
2946
|
+
removed: Object.keys(recorded).filter((path) => current[path] === void 0)
|
|
2947
|
+
};
|
|
2948
|
+
}
|
|
2949
|
+
const isUnchanged = (changes) => changes.changed.length + changes.added.length + changes.removed.length === 0;
|
|
2950
|
+
/** The differences as short lines for a person to read, capped. */
|
|
2951
|
+
function describeChanges(changes) {
|
|
2952
|
+
const lines = [
|
|
2953
|
+
...changes.changed.map((path) => `changed: ${path}`),
|
|
2954
|
+
...changes.added.map((path) => `added: ${path}`),
|
|
2955
|
+
...changes.removed.map((path) => `removed: ${path}`)
|
|
2956
|
+
];
|
|
2957
|
+
return lines.length <= MAX_LISTED_CHANGES ? lines : [...lines.slice(0, MAX_LISTED_CHANGES), `and ${lines.length - MAX_LISTED_CHANGES} more`];
|
|
2958
|
+
}
|
|
2959
|
+
/** How a world's files compare with the release it came from: the differences, or `unverified` when no record of the release exists. */
|
|
2960
|
+
async function localChanges(directory) {
|
|
2961
|
+
const origin = await readOrigin(directory);
|
|
2962
|
+
if (origin?.kind !== "release") return "unverified";
|
|
2963
|
+
return compare(origin.files, await hashWorld(directory));
|
|
2964
|
+
}
|
|
2965
|
+
//#endregion
|
|
2966
|
+
//#region src/host/import/snapshot.ts
|
|
2967
|
+
const SNAPSHOT = "files.json";
|
|
2968
|
+
/** The pictures of a world are fetched and generated in the background and are not what a card says. */
|
|
2969
|
+
const notTheCards = (path) => path.startsWith("images/");
|
|
2970
|
+
/** What a world's files were when its import was over; "changed since" is measured against it. */
|
|
2971
|
+
async function writeSnapshot(directory) {
|
|
2972
|
+
const file = join(directory, IMPORT_FOLDER, SNAPSHOT);
|
|
2973
|
+
await atomicWriteJson(file, await hashWorld(directory, notTheCards));
|
|
2974
|
+
}
|
|
2975
|
+
/** How a world compares with its snapshot: `no` for no change, `yes` with the files, and `unknown` when the import left no snapshot (an older import). */
|
|
2976
|
+
async function editsSince(directory) {
|
|
2977
|
+
let recorded;
|
|
2978
|
+
try {
|
|
2979
|
+
recorded = JSON.parse(await readFile(join(directory, IMPORT_FOLDER, SNAPSHOT), "utf8"));
|
|
2980
|
+
} catch (error) {
|
|
2981
|
+
if (error.code === "ENOENT") return { edited: "unknown" };
|
|
2982
|
+
throw error;
|
|
2983
|
+
}
|
|
2984
|
+
const changes = compare(recorded, await hashWorld(directory, notTheCards));
|
|
2985
|
+
return isUnchanged(changes) ? { edited: "no" } : {
|
|
2986
|
+
edited: "yes",
|
|
2987
|
+
changes: describeChanges(changes)
|
|
2988
|
+
};
|
|
2989
|
+
}
|
|
2990
|
+
//#endregion
|
|
2991
|
+
//#region src/host/import/provenance.ts
|
|
2992
|
+
const FILE = "provenance.json";
|
|
2993
|
+
const PROVENANCE_SCHEMA = "dsh-roleplay-import/v1";
|
|
2994
|
+
/** The import record of a world, or nothing for a world imported before records were kept. */
|
|
2995
|
+
async function readProvenance(directory) {
|
|
2996
|
+
let text;
|
|
2997
|
+
try {
|
|
2998
|
+
text = await readFile(join(directory, IMPORT_FOLDER, FILE), "utf8");
|
|
2999
|
+
} catch (error) {
|
|
3000
|
+
if (error.code === "ENOENT") return void 0;
|
|
3001
|
+
throw error;
|
|
3002
|
+
}
|
|
3003
|
+
const value = JSON.parse(text);
|
|
3004
|
+
if (value.schema !== "dsh-roleplay-import/v1" || !Array.isArray(value.history)) throw new Error(`${FILE} is not an import record this version reads`);
|
|
3005
|
+
return value;
|
|
3006
|
+
}
|
|
3007
|
+
/** Adds one line to the world's import record: what card it came from and, for an import, what was written. */
|
|
3008
|
+
async function recordProvenance(directory, entry, cardJson) {
|
|
3009
|
+
const earlier = await readProvenance(directory);
|
|
3010
|
+
const line = {
|
|
3011
|
+
...entry,
|
|
3012
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3013
|
+
card: {
|
|
3014
|
+
name: entry.card.name,
|
|
3015
|
+
sha256: createHash("sha256").update(cardJson).digest("hex")
|
|
3016
|
+
}
|
|
3017
|
+
};
|
|
3018
|
+
await atomicWriteJson(join(directory, IMPORT_FOLDER, FILE), {
|
|
3019
|
+
schema: PROVENANCE_SCHEMA,
|
|
3020
|
+
history: [...earlier?.history ?? [], line]
|
|
3021
|
+
});
|
|
3022
|
+
}
|
|
3023
|
+
//#endregion
|
|
3024
|
+
//#region src/host/import/run-import.ts
|
|
3025
|
+
/** The import in a world is not in the state the step needs, or there is none. The message says what to do. */
|
|
3026
|
+
var ImportStateError = class extends Error {};
|
|
3027
|
+
const PHASES = [
|
|
3028
|
+
"ready",
|
|
3029
|
+
"surveyed",
|
|
3030
|
+
"built",
|
|
3031
|
+
"repair",
|
|
3032
|
+
"done"
|
|
3033
|
+
];
|
|
3034
|
+
const STATE = "state.json";
|
|
3035
|
+
const CLASSIFICATION = "classification.json";
|
|
3036
|
+
const ROSTER = "roster.json";
|
|
3037
|
+
const EXTRACTED = "extracted.json";
|
|
3038
|
+
const PREVIOUS_EXTRACTED = "extracted.previous.json";
|
|
3039
|
+
const PICTURES = "pictures.json";
|
|
3040
|
+
const folder = (world) => join(world, IMPORT_FOLDER);
|
|
3041
|
+
async function readJson(file) {
|
|
3042
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
3043
|
+
}
|
|
3044
|
+
const writeJson = (file, value) => atomicWriteJson(file, value, { createDirectory: true });
|
|
3045
|
+
const fetching = /* @__PURE__ */ new Map();
|
|
3046
|
+
/**
|
|
3047
|
+
* Starts fetching the pictures the card points to, next to the work of the agents, once per import; a later call gets the same run or its saved result.
|
|
3048
|
+
* A failure is a report of its own: pictures never stop an import.
|
|
3049
|
+
*/
|
|
3050
|
+
function ensurePictures(world, urls) {
|
|
3051
|
+
const running = fetching.get(world);
|
|
3052
|
+
if (running !== void 0) return running;
|
|
3053
|
+
const run = (async () => {
|
|
3054
|
+
try {
|
|
3055
|
+
return await readJson(join(folder(world), PICTURES));
|
|
3056
|
+
} catch (error) {
|
|
3057
|
+
if (error.code !== "ENOENT") throw error;
|
|
3058
|
+
}
|
|
3059
|
+
const report = await fetchPictures(world, urls).catch((error) => ({
|
|
3060
|
+
found: 0,
|
|
3061
|
+
added: [],
|
|
3062
|
+
skipped: [{
|
|
3063
|
+
url: "",
|
|
3064
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
3065
|
+
}]
|
|
3066
|
+
}));
|
|
3067
|
+
await writeJson(join(folder(world), PICTURES), report);
|
|
3068
|
+
return report;
|
|
3069
|
+
})();
|
|
3070
|
+
fetching.set(world, run);
|
|
3071
|
+
run.catch(() => fetching.delete(world));
|
|
3072
|
+
return run;
|
|
3073
|
+
}
|
|
3074
|
+
/** How far the import of a world has come; nothing when the world holds no card waiting to be imported. */
|
|
3075
|
+
async function importPhase(world) {
|
|
3076
|
+
try {
|
|
3077
|
+
const state = await readJson(join(folder(world), STATE));
|
|
3078
|
+
return PHASES.includes(state.phase) ? state.phase : void 0;
|
|
3079
|
+
} catch (error) {
|
|
3080
|
+
if (error.code === "ENOENT") return void 0;
|
|
3081
|
+
throw error;
|
|
3082
|
+
}
|
|
3083
|
+
}
|
|
3084
|
+
/** Whether the import has just finished and its turn may still correct the world with the editing tools, without asking. */
|
|
3085
|
+
async function isReviewing(world) {
|
|
3086
|
+
try {
|
|
3087
|
+
return (await readJson(join(folder(world), STATE))).reviewing === true;
|
|
3088
|
+
} catch (error) {
|
|
3089
|
+
if (error.code === "ENOENT") return false;
|
|
3090
|
+
throw error;
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
/** The import turn is over: the world is edited like any other from now on, and what it holds now is what a later edit is measured against. */
|
|
3094
|
+
async function endReview(world) {
|
|
3095
|
+
if (!await isReviewing(world)) return;
|
|
3096
|
+
if ((await checkWorld({
|
|
3097
|
+
directory: world,
|
|
3098
|
+
summary: { name: "the world" }
|
|
3099
|
+
})).ok) await finishedImport(world);
|
|
3100
|
+
else await writeJson(join(folder(world), STATE), { phase: "repair" });
|
|
3101
|
+
}
|
|
3102
|
+
async function finishedImport(world) {
|
|
3103
|
+
await writeJson(join(folder(world), STATE), { phase: "done" });
|
|
3104
|
+
await writeSnapshot(world);
|
|
3105
|
+
}
|
|
3106
|
+
/** The person asked for a draft to be repaired: until the turn ends the assistant edits the world without asking, as it does in the review that follows an import. */
|
|
3107
|
+
async function startRepair(world) {
|
|
3108
|
+
if (await importPhase(world) === "repair") await writeJson(join(folder(world), STATE), {
|
|
3109
|
+
phase: "repair",
|
|
3110
|
+
reviewing: true
|
|
3111
|
+
});
|
|
3112
|
+
}
|
|
3113
|
+
/** A draft that has been repaired since (by the assistant or the person) becomes an ordinary world; one that still has problems stays as it is. @returns whether it is a world now. */
|
|
3114
|
+
async function settleDraft(world) {
|
|
3115
|
+
if (await importPhase(world) !== "repair") return false;
|
|
3116
|
+
if (!(await checkWorld({
|
|
3117
|
+
directory: world,
|
|
3118
|
+
summary: { name: "the world" }
|
|
3119
|
+
})).ok) return false;
|
|
3120
|
+
await finishedImport(world);
|
|
3121
|
+
return true;
|
|
3122
|
+
}
|
|
3123
|
+
/** The person accepts the draft as it is, problems included: it is an ordinary world from now on, which cannot be played until it is mended. */
|
|
3124
|
+
async function keepDraft(world) {
|
|
3125
|
+
if (await importPhase(world) !== "repair") throw new ImportStateError("this world is not a draft");
|
|
3126
|
+
await finishedImport(world);
|
|
3127
|
+
}
|
|
3128
|
+
/** Marks a folder that was just moved into a world as an import that is ready to run. */
|
|
3129
|
+
async function markReady(world) {
|
|
3130
|
+
await writeJson(join(folder(world), STATE), { phase: "ready" });
|
|
3131
|
+
}
|
|
3132
|
+
async function need(world, phases, step) {
|
|
3133
|
+
const phase = await importPhase(world);
|
|
3134
|
+
if (phase === void 0) throw new ImportStateError("no card is waiting to be imported in this world");
|
|
3135
|
+
if (!phases.includes(phase)) throw new ImportStateError(`${step} cannot run now: the import is at "${phase}"${phases.length === 0 ? "" : `; it needs "${phases.join("\" or \"")}"`}`);
|
|
3136
|
+
return phase;
|
|
3137
|
+
}
|
|
3138
|
+
async function load(world) {
|
|
3139
|
+
const { card, choices, hasPicture } = await readImportFolder(folder(world));
|
|
3140
|
+
return {
|
|
3141
|
+
card,
|
|
3142
|
+
choices,
|
|
3143
|
+
items: itemise(card, choices),
|
|
3144
|
+
picture: hasPicture
|
|
3145
|
+
};
|
|
3146
|
+
}
|
|
3147
|
+
/** First step: say what each piece of the card is, and list who and what the world is made of. */
|
|
3148
|
+
async function survey(ctx, world) {
|
|
3149
|
+
await need(world, [
|
|
3150
|
+
"ready",
|
|
3151
|
+
"surveyed",
|
|
3152
|
+
"built"
|
|
3153
|
+
], "the survey");
|
|
3154
|
+
const { card, items } = await load(world);
|
|
3155
|
+
ensurePictures(world, card.urls ?? []);
|
|
3156
|
+
const { classified, failures, decided } = await classifyItems(ctx, card, items);
|
|
3157
|
+
if (items.length > 0 && failures.length >= items.length && decided === 0) throw new Error(`no piece of the card could be read, so nothing was imported: ${failures[0]}`);
|
|
3158
|
+
const { roster, failure } = await buildRoster(ctx, card, items.filter((item) => !isLeftOut(classified[item.id])), classified);
|
|
3159
|
+
if (ctx.cancelled?.() === true) throw new Error("the survey was stopped before it was done, so what it made is not kept");
|
|
3160
|
+
await writeJson(join(folder(world), CLASSIFICATION), classified);
|
|
3161
|
+
await writeJson(join(folder(world), ROSTER), roster);
|
|
3162
|
+
await rm(join(folder(world), EXTRACTED), { force: true });
|
|
3163
|
+
await writeJson(join(folder(world), STATE), { phase: "surveyed" });
|
|
3164
|
+
const roles = {};
|
|
3165
|
+
for (const item of items) {
|
|
3166
|
+
const first = classified[item.id]?.roles[0];
|
|
3167
|
+
if (first !== void 0) roles[first] = (roles[first] ?? 0) + 1;
|
|
3168
|
+
}
|
|
3169
|
+
const names = (kind) => roster.filter((entity) => entity.kind === kind).map((entity) => entity.name);
|
|
3170
|
+
return {
|
|
3171
|
+
pieces: items.length,
|
|
3172
|
+
roles: Object.fromEntries(ROLES.filter((role) => roles[role] !== void 0).map((role) => [role, roles[role]])),
|
|
3173
|
+
leftOut: items.filter((item) => isLeftOut(classified[item.id])).length,
|
|
3174
|
+
roster: {
|
|
3175
|
+
characters: names("character"),
|
|
3176
|
+
places: names("place"),
|
|
3177
|
+
factions: names("faction"),
|
|
3178
|
+
things: names("thing")
|
|
3179
|
+
},
|
|
3180
|
+
playable: roster.find((entity) => entity.player)?.name,
|
|
3181
|
+
notes: [
|
|
3182
|
+
...failures,
|
|
3183
|
+
...decided === 0 ? [] : [`the decision model settled ${decided} of ${items.length} pieces as instructions or notes, without asking the language model`],
|
|
3184
|
+
...failure === void 0 ? [] : [failure]
|
|
3185
|
+
]
|
|
3186
|
+
};
|
|
3187
|
+
}
|
|
3188
|
+
/** Second step: write every character, place, faction, thing and background entry from the pieces that are about it. */
|
|
3189
|
+
async function build(ctx, world) {
|
|
3190
|
+
await need(world, ["surveyed", "built"], "the build");
|
|
3191
|
+
const { card, items } = await load(world);
|
|
3192
|
+
ensurePictures(world, card.urls ?? []);
|
|
3193
|
+
const classified = await readJson(join(folder(world), CLASSIFICATION));
|
|
3194
|
+
const roster = await readJson(join(folder(world), ROSTER));
|
|
3195
|
+
const extracted = await extractEntities(ctx, card, items.filter((item) => !isLeftOut(classified[item.id])), classified, roster);
|
|
3196
|
+
const style = await extractStyle(ctx, card, items, classified);
|
|
3197
|
+
extracted.prompts.push(...style.prompts);
|
|
3198
|
+
extracted.notes.push(...style.notes);
|
|
3199
|
+
const tracked = await extractVariables(ctx, card, items, classified, roster);
|
|
3200
|
+
extracted.variables.push(...tracked.variables);
|
|
3201
|
+
extracted.notes.push(...tracked.notes);
|
|
3202
|
+
const cast = await extractCasting(ctx, card, extracted.casting);
|
|
3203
|
+
extracted.commands.push(...cast.commands);
|
|
3204
|
+
extracted.triggers.push(...cast.triggers);
|
|
3205
|
+
extracted.notes.push(...cast.notes);
|
|
3206
|
+
if (ctx.cancelled?.() === true) throw new Error("the build was stopped before it was done, so what it made is not kept");
|
|
3207
|
+
await rename(join(folder(world), EXTRACTED), join(folder(world), PREVIOUS_EXTRACTED)).catch((error) => {
|
|
3208
|
+
if (error.code !== "ENOENT") throw error;
|
|
3209
|
+
});
|
|
3210
|
+
await writeJson(join(folder(world), EXTRACTED), extracted);
|
|
3211
|
+
await writeJson(join(folder(world), STATE), { phase: "built" });
|
|
3212
|
+
return {
|
|
3213
|
+
characters: extracted.characters.length,
|
|
3214
|
+
places: extracted.locations.length,
|
|
3215
|
+
factions: extracted.factions.length,
|
|
3216
|
+
things: extracted.items.length,
|
|
3217
|
+
lore: extracted.lore.length,
|
|
3218
|
+
prompts: extracted.prompts.map((entry) => entry.id),
|
|
3219
|
+
variables: extracted.variables.length,
|
|
3220
|
+
notes: extracted.notes
|
|
3221
|
+
};
|
|
3222
|
+
}
|
|
3223
|
+
/** Last step: write the staged world and check it as a whole; a world that cannot start yet is kept as a repairable draft. */
|
|
3224
|
+
async function finish(ctx, world) {
|
|
3225
|
+
await need(world, ["built"], "the finish");
|
|
3226
|
+
const { card, choices, items, picture } = await load(world);
|
|
3227
|
+
const classified = await readJson(join(folder(world), CLASSIFICATION));
|
|
3228
|
+
const roster = await readJson(join(folder(world), ROSTER));
|
|
3229
|
+
const extracted = {
|
|
3230
|
+
...emptyExtracted(),
|
|
3231
|
+
...await readJson(join(folder(world), EXTRACTED)).catch(() => ({}))
|
|
3232
|
+
};
|
|
3233
|
+
const pictures = await ensurePictures(world, card.urls ?? []);
|
|
3234
|
+
const result = await finishImport(ctx, {
|
|
3235
|
+
directory: world,
|
|
3236
|
+
card,
|
|
3237
|
+
choices,
|
|
3238
|
+
roster,
|
|
3239
|
+
items,
|
|
3240
|
+
classified,
|
|
3241
|
+
extracted,
|
|
3242
|
+
...picture ? { picture: await readFile(join(folder(world), PICTURE_FILE)) } : {},
|
|
3243
|
+
notes: [],
|
|
3244
|
+
pictures: {
|
|
3245
|
+
found: pictures.found,
|
|
3246
|
+
added: pictures.added.length
|
|
3247
|
+
}
|
|
3248
|
+
});
|
|
3249
|
+
if (result.ok) {
|
|
3250
|
+
await writeJson(join(folder(world), STATE), {
|
|
3251
|
+
phase: result.draft === void 0 ? "done" : "repair",
|
|
3252
|
+
reviewing: true
|
|
3253
|
+
});
|
|
3254
|
+
await recordProvenance(world, {
|
|
3255
|
+
kind: "import",
|
|
3256
|
+
card: { name: card.name },
|
|
3257
|
+
language: ctx.language ?? "",
|
|
3258
|
+
counts: result.report.counts,
|
|
3259
|
+
notes: result.report.notes.length
|
|
3260
|
+
}, await readFile(join(folder(world), "card.json"), "utf8"));
|
|
3261
|
+
}
|
|
3262
|
+
return result;
|
|
3263
|
+
}
|
|
3264
|
+
//#endregion
|
|
3265
|
+
//#region src/host/import/tools.ts
|
|
3266
|
+
const SURVEY_TOOL = "import_survey";
|
|
3267
|
+
const BUILD_TOOL = "import_build";
|
|
3268
|
+
const FINISH_TOOL = "import_finish";
|
|
3269
|
+
/** How many times a turn that has not finished the import is sent back to it. */
|
|
3270
|
+
const MAX_OBJECTIONS = 3;
|
|
3271
|
+
/** How often a turn that left the world unable to start is sent back to mend it: each round can show a part of the world that was hidden behind the last one. */
|
|
3272
|
+
const MAX_REPAIRS = 5;
|
|
3273
|
+
/** The build is the slow step (minutes, one agent per entity); a turn that needs it more often than this is not converging on a card that will finish. */
|
|
3274
|
+
const MAX_BUILDS_PER_TURN = 2;
|
|
3275
|
+
/** A model call that fails is made once more before the piece it was for is given up. */
|
|
3276
|
+
const ATTEMPTS = 2;
|
|
3277
|
+
/** Room added to every job's own budget: the model often writes out its analysis before the answer, and a budget that fits the answer alone is used up before the answer is given (found live: a job of 4000 tokens failed three of four times, and none at 12000). The setting stays the ceiling. */
|
|
3278
|
+
const ANALYSIS_TOKENS = 6e3;
|
|
3279
|
+
const CARD = `${IMPORT_FOLDER}/card.json`;
|
|
3280
|
+
const cardParameter = {
|
|
3281
|
+
type: "string",
|
|
3282
|
+
required: true,
|
|
3283
|
+
description: `The card to import: the path that follows /import-st in the person's message (${CARD}).`
|
|
3284
|
+
};
|
|
3285
|
+
/** A model that is asked for a tool with nothing to fill in tends to write its name as text instead of calling it: naming the card gives it something to say. */
|
|
3286
|
+
function checkedCard(args) {
|
|
3287
|
+
if (args.card.trim() !== CARD) throw new Error(`the card to import is ${CARD}`);
|
|
3288
|
+
}
|
|
3289
|
+
const output = (render) => ({
|
|
3290
|
+
schema: { type: "json" },
|
|
3291
|
+
render: (_args, value) => [{
|
|
3292
|
+
type: "text",
|
|
3293
|
+
text: render(value)
|
|
3294
|
+
}]
|
|
3295
|
+
});
|
|
3296
|
+
const json = (value) => JSON.parse(JSON.stringify(value));
|
|
3297
|
+
/** The runner of an import: every job is a narrow agent below the chat's own, on the chat's model. */
|
|
3298
|
+
function contextOf(exec, settings, text, language) {
|
|
3299
|
+
const agent = exec.agent;
|
|
3300
|
+
if (agent === void 0) throw new Error("the import tools can only be called by an agent");
|
|
3301
|
+
const run = async (job) => {
|
|
3302
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
3303
|
+
const named = namedModel(settings.model);
|
|
3304
|
+
const ceiling = await outputCeiling(settings.maxTokens, agent, named.model, exec.signal);
|
|
3305
|
+
return await runChild({
|
|
3306
|
+
parent: agent,
|
|
3307
|
+
signal: exec.signal,
|
|
3308
|
+
persona: job.persona,
|
|
3309
|
+
prompt: job.prompt,
|
|
3310
|
+
result: job.result,
|
|
3311
|
+
...job.check === void 0 ? {} : { beforeSubmit: (value) => job.check?.(value) },
|
|
3312
|
+
maxTokens: Math.min((job.maxTokens ?? ceiling) + ANALYSIS_TOKENS, ceiling),
|
|
3313
|
+
timeoutMinutes: settings.timeoutMinutes,
|
|
3314
|
+
...named,
|
|
3315
|
+
...settings.structured === "schema" ? { structured: true } : {},
|
|
3316
|
+
sampling: {
|
|
3317
|
+
temperature: settings.temperature,
|
|
3318
|
+
toolChoice: "required"
|
|
3319
|
+
},
|
|
3320
|
+
...settings.reasoning === "" ? {} : { reasoningEffort: settings.reasoning }
|
|
3321
|
+
});
|
|
3322
|
+
} catch (error) {
|
|
3323
|
+
if (exec.signal.aborted || attempt >= ATTEMPTS || error instanceof ChildTimeoutError) throw error;
|
|
3324
|
+
}
|
|
3325
|
+
};
|
|
3326
|
+
const decide = settings.decisions === "decision" ? (state, asks) => {
|
|
3327
|
+
const service = agent.ctx.get("decisions");
|
|
3328
|
+
if (service === void 0) return Promise.reject(/* @__PURE__ */ new Error("no decision service is selected, or the selected one is not loaded"));
|
|
3329
|
+
return askYesNo(service, state, asks, exec.signal);
|
|
3330
|
+
} : void 0;
|
|
3331
|
+
return {
|
|
3332
|
+
run,
|
|
3333
|
+
cancelled: () => exec.signal.aborted,
|
|
3334
|
+
concurrency: settings.concurrency,
|
|
3335
|
+
variablesPerRequest: settings.variablesPerRequest,
|
|
3336
|
+
text,
|
|
3337
|
+
...language === void 0 ? {} : { language },
|
|
3338
|
+
say: () => void 0,
|
|
3339
|
+
...decide === void 0 ? {} : {
|
|
3340
|
+
decide,
|
|
3341
|
+
confidence: settings.confidence
|
|
3342
|
+
}
|
|
3343
|
+
};
|
|
3344
|
+
}
|
|
3345
|
+
async function worldOf(worlds, exec) {
|
|
3346
|
+
const chat = exec.agent?.session.id;
|
|
3347
|
+
const worldId = chat === void 0 ? void 0 : authoredWorldOf(chat);
|
|
3348
|
+
if (worldId === void 0) throw new Error("the import tools are available only in a world authoring chat");
|
|
3349
|
+
const record = await worlds.find(worldId);
|
|
3350
|
+
if (record === void 0) throw new Error(`the authored world "${worldId}" no longer exists`);
|
|
3351
|
+
return {
|
|
3352
|
+
id: worldId,
|
|
3353
|
+
directory: record.directory
|
|
3354
|
+
};
|
|
3355
|
+
}
|
|
3356
|
+
const toolNames = {
|
|
3357
|
+
survey: SURVEY_TOOL,
|
|
3358
|
+
build: BUILD_TOOL,
|
|
3359
|
+
finish: FINISH_TOOL
|
|
3360
|
+
};
|
|
3361
|
+
/** The three steps of an import, as tools of the authoring chat. They do their work in agents of their own, one narrow job each. */
|
|
3362
|
+
function importTools(worlds, settings, prompting) {
|
|
3363
|
+
const builds = /* @__PURE__ */ new Map();
|
|
3364
|
+
/** Runs one step for the world of the calling chat; what the model should do next is told in the result, in the person's language. */
|
|
3365
|
+
const step = async (exec, work, next) => {
|
|
3366
|
+
const world = await worldOf(worlds, exec);
|
|
3367
|
+
const language = prompting.languages().get(world.id);
|
|
3368
|
+
const text = (id, variables) => prompting.prompts().text(id, language, {
|
|
3369
|
+
...toolNames,
|
|
3370
|
+
...variables
|
|
3371
|
+
});
|
|
3372
|
+
const result = await work(contextOf(exec, settings(), text, language), world.directory);
|
|
3373
|
+
return json({
|
|
3374
|
+
...result,
|
|
3375
|
+
next: next(text, result)
|
|
3376
|
+
});
|
|
3377
|
+
};
|
|
3378
|
+
return [
|
|
3379
|
+
defineTool({
|
|
3380
|
+
name: SURVEY_TOOL,
|
|
3381
|
+
description: "Step 1 of importing a character card into this world: read every piece of the card, say what each is (character, place, background, instruction…), and list who and what the world is made of. Takes a few minutes. Only in an import turn.",
|
|
3382
|
+
parameters: { card: cardParameter },
|
|
3383
|
+
output: output((value) => JSON.stringify(value, null, 1)),
|
|
3384
|
+
isConcurrencySafe: () => false,
|
|
3385
|
+
async execute(args, exec) {
|
|
3386
|
+
checkedCard(args);
|
|
3387
|
+
return await step(exec, survey, (text) => text("import/next-survey"));
|
|
3388
|
+
}
|
|
3389
|
+
}),
|
|
3390
|
+
defineTool({
|
|
3391
|
+
name: BUILD_TOOL,
|
|
3392
|
+
description: "Step 2 of importing a character card: write every character, place, organisation, object and background entry from the pieces of the card that are about it. Takes several minutes. Run after the survey.",
|
|
3393
|
+
parameters: { card: cardParameter },
|
|
3394
|
+
output: output((value) => JSON.stringify(value, null, 1)),
|
|
3395
|
+
isConcurrencySafe: () => false,
|
|
3396
|
+
async execute(args, exec) {
|
|
3397
|
+
checkedCard(args);
|
|
3398
|
+
const chat = exec.agent?.session.id ?? "";
|
|
3399
|
+
const turn = exec.agent === void 0 ? 0 : currentTurn(exec.agent);
|
|
3400
|
+
const seen = builds.get(chat);
|
|
3401
|
+
const count = seen?.turn === turn ? seen.count + 1 : 1;
|
|
3402
|
+
if (count > MAX_BUILDS_PER_TURN) throw new Error(`the build has already run ${MAX_BUILDS_PER_TURN} times in this turn: do not run it again, tell the person what is wrong and stop`);
|
|
3403
|
+
builds.set(chat, {
|
|
3404
|
+
turn,
|
|
3405
|
+
count
|
|
3406
|
+
});
|
|
3407
|
+
return await step(exec, build, (text) => text("import/next-build"));
|
|
3408
|
+
}
|
|
3409
|
+
}),
|
|
3410
|
+
defineTool({
|
|
3411
|
+
name: FINISH_TOOL,
|
|
3412
|
+
description: "Step 3 of importing a character card: write the world together with its description, tags, opening and cover, check whether a story can start from it, and report what was imported. A world that still has problems is kept as a repairable draft. Run after the build.",
|
|
3413
|
+
parameters: { card: cardParameter },
|
|
3414
|
+
output: output((value) => JSON.stringify(value, null, 1)),
|
|
3415
|
+
isConcurrencySafe: () => false,
|
|
3416
|
+
async execute(args, exec) {
|
|
3417
|
+
checkedCard(args);
|
|
3418
|
+
return await step(exec, finish, (text, result) => text(result.ok ? result.draft === void 0 ? "import/finish-ok" : "import/finish-draft" : "import/finish-failed"));
|
|
3419
|
+
}
|
|
3420
|
+
})
|
|
3421
|
+
];
|
|
3422
|
+
}
|
|
3423
|
+
/** The procedure of an import turn, told to the chat in place of what it does for any other message. */
|
|
3424
|
+
function importNotice(phase, text) {
|
|
3425
|
+
if (phase === void 0) return text("import/notice-missing");
|
|
3426
|
+
if (phase === "repair") return text("import/notice-repair");
|
|
3427
|
+
return text("import/notice", {
|
|
3428
|
+
card: CARD,
|
|
3429
|
+
phase,
|
|
3430
|
+
done: phase === "done" ? text("import/notice-done") : ""
|
|
3431
|
+
});
|
|
3432
|
+
}
|
|
3433
|
+
/** Hears the `/import-st` command in an authoring chat, makes that turn an import turn, and does not let it end before the import is done. */
|
|
3434
|
+
function importHooks(ctx, worlds, prompting) {
|
|
3435
|
+
const textFor = (worldId) => (id, variables) => prompting.prompts().text(id, worldId === void 0 ? void 0 : prompting.languages().get(worldId), {
|
|
3436
|
+
...toolNames,
|
|
3437
|
+
...variables
|
|
3438
|
+
});
|
|
3439
|
+
const imports = /* @__PURE__ */ new Map();
|
|
3440
|
+
const objections = /* @__PURE__ */ new Map();
|
|
3441
|
+
const repairs = /* @__PURE__ */ new Map();
|
|
3442
|
+
const authoring = (agent) => agent.session.header.origin === "subagent" || authoredWorldOf(agent.session.id) === void 0 ? void 0 : agent.session.id;
|
|
3443
|
+
ctx.on("agent/pre-step", async (payload, next) => {
|
|
3444
|
+
const decision = await next();
|
|
3445
|
+
const chat = authoring(payload.agent);
|
|
3446
|
+
if (decision.kind !== "enter" || payload.step !== 1 || chat === void 0) return decision;
|
|
3447
|
+
const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
|
|
3448
|
+
if (parseImportCommand(text) === void 0) return decision;
|
|
3449
|
+
const worldId = authoredWorldOf(chat);
|
|
3450
|
+
const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
|
|
3451
|
+
const phase = record === void 0 ? void 0 : await importPhase(record.directory);
|
|
3452
|
+
if (phase !== void 0 && phase !== "done") {
|
|
3453
|
+
imports.set(chat, payload.turn);
|
|
3454
|
+
objections.delete(chat);
|
|
3455
|
+
repairs.delete(chat);
|
|
3456
|
+
}
|
|
3457
|
+
if (phase === "repair" && record !== void 0) await startRepair(record.directory);
|
|
3458
|
+
return {
|
|
3459
|
+
...decision,
|
|
3460
|
+
messages: [...decision.messages, createUserMessage({
|
|
3461
|
+
content: [{
|
|
3462
|
+
type: "text",
|
|
3463
|
+
text: importNotice(phase, textFor(worldId))
|
|
3464
|
+
}],
|
|
3465
|
+
source: { kind: "roleplay" }
|
|
3466
|
+
})]
|
|
3467
|
+
};
|
|
3468
|
+
});
|
|
3469
|
+
ctx.on("session/event", async (session, event) => {
|
|
3470
|
+
if (event.type !== "turn/end" || session.header.origin === "subagent") return;
|
|
3471
|
+
const worldId = authoredWorldOf(session.id);
|
|
3472
|
+
const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
|
|
3473
|
+
if (record === void 0) return;
|
|
3474
|
+
await endReview(record.directory);
|
|
3475
|
+
await settleDraft(record.directory);
|
|
3476
|
+
});
|
|
3477
|
+
ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
|
|
3478
|
+
const chat = authoring(agent);
|
|
3479
|
+
if (chat === void 0 || imports.get(chat) !== turn) return;
|
|
3480
|
+
const worldId = authoredWorldOf(chat);
|
|
3481
|
+
const record = worldId === void 0 ? void 0 : await worlds.find(worldId);
|
|
3482
|
+
const phase = record === void 0 ? void 0 : await importPhase(record.directory);
|
|
3483
|
+
if (record !== void 0 && (phase === "repair" || phase === "done" && await isReviewing(record.directory))) {
|
|
3484
|
+
const check = await checkWorld({
|
|
3485
|
+
directory: record.directory,
|
|
3486
|
+
summary: { name: record.summary.name }
|
|
3487
|
+
});
|
|
3488
|
+
const mended = repairs.get(chat) ?? 0;
|
|
3489
|
+
if (check.ok || mended >= MAX_REPAIRS) {
|
|
3490
|
+
imports.delete(chat);
|
|
3491
|
+
repairs.delete(chat);
|
|
3492
|
+
return;
|
|
3493
|
+
}
|
|
3494
|
+
repairs.set(chat, mended + 1);
|
|
3495
|
+
agent.steer(createUserMessage({
|
|
3496
|
+
content: [{
|
|
3497
|
+
type: "text",
|
|
3498
|
+
text: textFor(worldId)("import/repair-again", { problems: check.problems.map((problem) => `- ${problem.where}: ${problem.message}`).join("\n") + (check.more > 0 ? `\n(and ${check.more} more)` : "") })
|
|
3499
|
+
}],
|
|
3500
|
+
source: { kind: "roleplay" }
|
|
3501
|
+
}));
|
|
3502
|
+
return;
|
|
3503
|
+
}
|
|
3504
|
+
if (phase === void 0 || phase === "done") {
|
|
3505
|
+
imports.delete(chat);
|
|
3506
|
+
return;
|
|
3507
|
+
}
|
|
3508
|
+
const told = objections.get(chat) ?? 0;
|
|
3509
|
+
if (told >= MAX_OBJECTIONS) {
|
|
3510
|
+
imports.delete(chat);
|
|
3511
|
+
return;
|
|
3512
|
+
}
|
|
3513
|
+
objections.set(chat, told + 1);
|
|
3514
|
+
const next = phase === "ready" ? SURVEY_TOOL : phase === "surveyed" ? BUILD_TOOL : FINISH_TOOL;
|
|
3515
|
+
agent.steer(createUserMessage({
|
|
3516
|
+
content: [{
|
|
3517
|
+
type: "text",
|
|
3518
|
+
text: textFor(worldId)("import/steer", {
|
|
3519
|
+
phase,
|
|
3520
|
+
next,
|
|
3521
|
+
card: CARD
|
|
3522
|
+
})
|
|
3523
|
+
}],
|
|
3524
|
+
source: { kind: "roleplay" }
|
|
3525
|
+
}));
|
|
3526
|
+
});
|
|
3527
|
+
}
|
|
3528
|
+
//#endregion
|
|
3529
|
+
//#region src/shared/import-selection.ts
|
|
3530
|
+
const MAX_PREVIEW_TEXT = 4e3;
|
|
3531
|
+
//#endregion
|
|
3532
|
+
//#region src/host/tools/authoring-tools.ts
|
|
3533
|
+
/** Which of the tools other plugins registered for everyone each assistant of the authoring chats was given in the settings; read afresh, so a change applies at its next step. */
|
|
3534
|
+
var AuthoringTools = class extends Service {
|
|
3535
|
+
board;
|
|
3536
|
+
constructor(ctx, board) {
|
|
3537
|
+
super(ctx, "roleplayAuthoringTools");
|
|
3538
|
+
this.board = board;
|
|
3539
|
+
}
|
|
3540
|
+
/** What the assistant is given: the tools it may call on top of its own. */
|
|
3541
|
+
given(registry, kind) {
|
|
3542
|
+
return externalGiven(registry, this.board(), kind);
|
|
3543
|
+
}
|
|
3544
|
+
/** What the assistant is not given and so does not see. */
|
|
3545
|
+
withheld(registry, kind) {
|
|
3546
|
+
return externalWithheld(registry, this.board(), kind);
|
|
3547
|
+
}
|
|
3548
|
+
};
|
|
3549
|
+
/**
|
|
3550
|
+
* Takes the tools of other plugins away from an assistant of an authoring chat unless the settings gave it that tool, before its first request and again
|
|
3551
|
+
* at every step (a server may connect later). Helpers the assistant starts are not touched: they have no tools but their own.
|
|
3552
|
+
*/
|
|
3553
|
+
function limitAuthoringAgent(agent, kind, tools) {
|
|
3554
|
+
externalToolLimit(agent, tools.withheld(agent.ctx.tools, kind));
|
|
3555
|
+
}
|
|
3556
|
+
/** Installs the limit on the agents of the chats `kindOf` recognises, which a preset's listeners find among the agents of every chat of the preset and its helpers. */
|
|
3557
|
+
function limitAuthoringAgents(ctx, kindOf) {
|
|
3558
|
+
const apply = (agent) => {
|
|
3559
|
+
if (agent.session.header.origin === "subagent") return;
|
|
3560
|
+
const kind = kindOf(agent.session.id);
|
|
3561
|
+
if (kind !== void 0) limitAuthoringAgent(agent, kind, ctx.roleplayAuthoringTools);
|
|
3562
|
+
};
|
|
3563
|
+
ctx.on("agent/created", ({ agent }) => {
|
|
3564
|
+
apply(agent);
|
|
3565
|
+
});
|
|
3566
|
+
ctx.on("agent/pre-step", async (payload, next) => {
|
|
3567
|
+
apply(payload.agent);
|
|
3568
|
+
return await next();
|
|
3569
|
+
});
|
|
3570
|
+
}
|
|
3571
|
+
//#endregion
|
|
3572
|
+
export { knowsCharacter as $, alternateOpenings as A, loadCharacters as At, deleteLorebook as B, authoredWorldOf as Bt, addressKey as C, DICE_FILE_NAME as Ct, guardedLookup as D, loadCalendar as Dt, fetchPictures as E, CALENDAR_FILE_NAME as Et, WORLD_FILE_NAME as F, pictureOf as Ft, loadLorebook as G, entriesOf as H, parseWorldFile as I, readCard as It, reserveLorebook as J, lorebookDirectory as K, parseWorldInfoEdit as L, DICE_COMPARISONS as Lt, openingMessage as M, knownOutputCeiling as Mt, writePortrait as N, ImportCardError as Nt, mergeReports as O, parseCalendarFile as Ot, serialized as P, isPng as Pt, loadValidatedWorld as Q, addLorebookEntries as R, DICE_READINGS as Rt, CatalogueError as S, loadFactions as St, candidateUrls as T, parseDiceFile as Tt, isLorebookName as U, deleteLorebookEntry as V, authoringChatSessionId as Vt, listLorebooks as W, writeLorebookEntry as X, updateLorebookInfo as Y, checkWorld as Z, hashWorld as _, LOCATIONS_DIR as _t, importHooks as a, populateItems as at, readOrigin as b, loadItems as bt, importPhase as c, populateLore as ct, markReady as d, populateVariables as dt, populateCalendar as et, settleDraft as f, routineProblems as ft, describeChanges as g, loadLore as gt, writeSnapshot as h, LORE_DIR as ht, contextOf as i, populateFactions as it, cardCharacter as j, subfolders as jt, vetUrl as k, CHARACTERS_DIR as kt, isReviewing as l, populateRoutines as lt, editsSince as m, loadTriggers as mt, limitAuthoringAgents as n, populateClock as nt, importTools as o, populateKnowledge as ot, recordProvenance as p, TRIGGERS_FILE_NAME as pt, readLorebook as q, MAX_PREVIEW_TEXT as r, populateDice as rt, worldOf as s, populateLocations as st, AuthoringTools as t, populateCharacters as tt, keepDraft as u, populateTriggers as ut, isUnchanged as v, loadLocations as vt, addressesToFetch as w, loadDice as wt, writeOrigin as x, FACTIONS_DIR as xt, localChanges as y, ITEMS_DIR as yt, createLorebook as z, DICE_RESULTS as zt };
|
|
3573
|
+
|
|
3574
|
+
//# sourceMappingURL=authoring-tools-DNnx0Nts.js.map
|