@dsh-agentic-roleplay/core 0.7.3 → 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-CIsWbq0B.js → authoring-tools-DNnx0Nts.js} +1774 -4517
- package/lib/authoring.js +51 -9
- package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
- package/lib/client.js +661 -427
- package/lib/client.js.map +1 -1
- package/lib/compaction.js +2 -2
- package/lib/doctor.js +2 -2
- package/lib/{gallery-DmBZ2L5l.js → gallery-D9nG3C78.js} +2 -2
- package/lib/{generator-BmdoTIL2.js → generator-r1Czm7oi.js} +2 -2
- package/lib/helper.js +1 -1
- package/lib/{hooks-C8eELrni.js → hooks-BQCzgggH.js} +92 -8
- package/lib/images.js +4 -4
- package/lib/index.js +920 -739
- package/lib/{library-lVNf9qG_.js → library-zI-2tG7h.js} +25 -8
- package/lib/{lorebook-author-tools-BDOs4i5C.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-DeTscGT2.js → pack-jail-5EJ-WYyW.js} +30 -68
- package/lib/{packs-CY8ms8v_.js → packs-Cv8hanXJ.js} +2 -2
- package/lib/{presenter-agent-cFR4sos3.js → presenter-agent-BSaMSd3G.js} +6 -6
- package/lib/{preset-n4-j6k4S.js → preset-CWI3-0r1.js} +4 -3
- package/lib/{preset-author-tools-2m4BLtws.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-CJB5s0ip.js → reflection-zSaMsjKj.js} +127 -127
- package/lib/{text-Cwl5s0j0.js → text-BzudpQLS.js} +9 -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/route-C6SHz9j2.js +0 -518
|
@@ -0,0 +1,3998 @@
|
|
|
1
|
+
import { i as VARIABLE_VISIBILITIES, n as VARIABLE_KINDS, r as VARIABLE_SUBJECTS } from "./access-DtOxFKBK.js";
|
|
2
|
+
import "./narration-CnBlVure.js";
|
|
3
|
+
import { J as formatIssue, K as readDocument, X as LANGUAGE_FOLDER, Y as errorMessage, Z as PROMPTS_FOLDER, at as shippedPromptsDirectory, it as shippedLanguages, nt as listFiles, q as Reader, rt as promptProblem, tt as languageOf } from "./hooks-BQCzgggH.js";
|
|
4
|
+
import { u as parseSampling } from "./child-D6mpkkCE.js";
|
|
5
|
+
import { C as trOf, S as slug, b as mapLimit, w as uniqueKey, x as norm } from "./library-zI-2tG7h.js";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
7
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
8
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
9
|
+
import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
10
|
+
import { MAX_ROUTINE_WINDOWS, createSessionStore, dayTokenProblems, valueIssue } from "@dsh-agentic-roleplay/state";
|
|
11
|
+
//#region ../dsh-roleplay-model/src/character.ts
|
|
12
|
+
const CHARACTER_ROLES = ["playable", "npc"];
|
|
13
|
+
const CHARACTER_TIERS = [
|
|
14
|
+
"principal",
|
|
15
|
+
"supporting",
|
|
16
|
+
"background"
|
|
17
|
+
];
|
|
18
|
+
const CHARACTER_KINDS = ["person", "group"];
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region ../dsh-roleplay-model/src/intent.ts
|
|
21
|
+
const INTENT_TYPES = [
|
|
22
|
+
"need",
|
|
23
|
+
"obligation",
|
|
24
|
+
"quest",
|
|
25
|
+
"agenda",
|
|
26
|
+
"aspiration",
|
|
27
|
+
"relationship",
|
|
28
|
+
"habit",
|
|
29
|
+
"reaction"
|
|
30
|
+
];
|
|
31
|
+
const INTENT_STATUSES = [
|
|
32
|
+
"active",
|
|
33
|
+
"paused",
|
|
34
|
+
"completed",
|
|
35
|
+
"failed",
|
|
36
|
+
"abandoned"
|
|
37
|
+
];
|
|
38
|
+
const INTENT_HORIZONS = [
|
|
39
|
+
"immediate",
|
|
40
|
+
"short",
|
|
41
|
+
"day",
|
|
42
|
+
"long",
|
|
43
|
+
"open_ended"
|
|
44
|
+
];
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region ../dsh-roleplay-model/src/item.ts
|
|
47
|
+
/** Whether a container can be got into. */
|
|
48
|
+
const CONTAINER_STATES = [
|
|
49
|
+
"open",
|
|
50
|
+
"closed",
|
|
51
|
+
"locked"
|
|
52
|
+
];
|
|
53
|
+
const SLOT_ID = /^[a-z][a-z0-9_-]{0,39}$/;
|
|
54
|
+
const DEFAULT_SLOTS = [
|
|
55
|
+
{
|
|
56
|
+
id: "head",
|
|
57
|
+
name: "head",
|
|
58
|
+
capacity: 1
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
id: "face",
|
|
62
|
+
name: "face",
|
|
63
|
+
capacity: 1
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
id: "neck",
|
|
67
|
+
name: "neck",
|
|
68
|
+
capacity: 1
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
id: "torso",
|
|
72
|
+
name: "torso",
|
|
73
|
+
capacity: 2
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
id: "back",
|
|
77
|
+
name: "back",
|
|
78
|
+
capacity: 1
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
id: "waist",
|
|
82
|
+
name: "waist",
|
|
83
|
+
capacity: 1
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
id: "hands",
|
|
87
|
+
name: "hands",
|
|
88
|
+
capacity: 1
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: "wrists",
|
|
92
|
+
name: "wrists",
|
|
93
|
+
capacity: 2
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
id: "fingers",
|
|
97
|
+
name: "fingers",
|
|
98
|
+
capacity: 4
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: "legs",
|
|
102
|
+
name: "legs",
|
|
103
|
+
capacity: 1
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
id: "feet",
|
|
107
|
+
name: "feet",
|
|
108
|
+
capacity: 1
|
|
109
|
+
}
|
|
110
|
+
];
|
|
111
|
+
//#endregion
|
|
112
|
+
//#region ../dsh-roleplay-model/src/location.ts
|
|
113
|
+
/** Whether people can go through an exit now. */
|
|
114
|
+
const EXIT_STATES = [
|
|
115
|
+
"open",
|
|
116
|
+
"locked",
|
|
117
|
+
"blocked"
|
|
118
|
+
];
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region ../dsh-roleplay-model/src/faction.ts
|
|
121
|
+
const MEMBERSHIP_STATUSES = [
|
|
122
|
+
"active",
|
|
123
|
+
"inactive",
|
|
124
|
+
"former"
|
|
125
|
+
];
|
|
126
|
+
//#endregion
|
|
127
|
+
//#region ../dsh-roleplay-model/src/agenda.ts
|
|
128
|
+
const WEEKDAY_NAMES = [
|
|
129
|
+
"sun",
|
|
130
|
+
"mon",
|
|
131
|
+
"tue",
|
|
132
|
+
"wed",
|
|
133
|
+
"thu",
|
|
134
|
+
"fri",
|
|
135
|
+
"sat"
|
|
136
|
+
];
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region ../dsh-roleplay-model/src/lore.ts
|
|
139
|
+
const LORE_KINDS = [
|
|
140
|
+
"history",
|
|
141
|
+
"culture",
|
|
142
|
+
"religion",
|
|
143
|
+
"politics",
|
|
144
|
+
"geography",
|
|
145
|
+
"science",
|
|
146
|
+
"custom",
|
|
147
|
+
"legend",
|
|
148
|
+
"other"
|
|
149
|
+
];
|
|
150
|
+
/** Who knows an entry: `everyone` is common knowledge of the story's world, `listed` only the characters that have a knowledge edge to it (the game master always reads all of it). */
|
|
151
|
+
const LORE_SCOPES = ["everyone", "listed"];
|
|
152
|
+
const LORE_SUBJECT_KINDS = [
|
|
153
|
+
"character",
|
|
154
|
+
"faction",
|
|
155
|
+
"location",
|
|
156
|
+
"item",
|
|
157
|
+
"lore"
|
|
158
|
+
];
|
|
159
|
+
//#endregion
|
|
160
|
+
//#region src/shared/world-state.ts
|
|
161
|
+
/** The problems with an edit, for the person who made it; nothing was changed. */
|
|
162
|
+
var InvalidEditProblems = class extends Error {
|
|
163
|
+
problems;
|
|
164
|
+
constructor(problems) {
|
|
165
|
+
super(`the edit is not acceptable: ${problems.join("; ")}`);
|
|
166
|
+
this.problems = problems;
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
const TEXT_LIMIT = 2e4;
|
|
170
|
+
const NAME_LIMIT = 200;
|
|
171
|
+
/** Reads an edit from what the browser sent: every unknown or mistyped field is a problem. */
|
|
172
|
+
function parseCharacterEdit(value) {
|
|
173
|
+
const problems = [];
|
|
174
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
|
|
175
|
+
const input = value;
|
|
176
|
+
const edit = {};
|
|
177
|
+
const text = (source, key, path, limit) => {
|
|
178
|
+
const found = source[key];
|
|
179
|
+
if (found === void 0) return void 0;
|
|
180
|
+
if (typeof found !== "string") {
|
|
181
|
+
problems.push(`${path}${key} must be text`);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (found.length > limit) {
|
|
185
|
+
problems.push(`${path}${key} is longer than ${limit} characters`);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
return found;
|
|
189
|
+
};
|
|
190
|
+
const list = (source, key, path) => {
|
|
191
|
+
const found = source[key];
|
|
192
|
+
if (found === void 0) return void 0;
|
|
193
|
+
if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= NAME_LIMIT) || found.length > 50) {
|
|
194
|
+
problems.push(`${path}${key} must be a list of short texts`);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
return found;
|
|
198
|
+
};
|
|
199
|
+
const choice = (key, options, source = input, path = "") => {
|
|
200
|
+
const found = source[key];
|
|
201
|
+
if (found === void 0) return void 0;
|
|
202
|
+
if (typeof found !== "string" || !options.includes(found)) {
|
|
203
|
+
problems.push(`${path}${key} must be one of: ${options.join(", ")}`);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
return found;
|
|
207
|
+
};
|
|
208
|
+
const allowed = (source, keys, path) => {
|
|
209
|
+
for (const key of Object.keys(source)) if (!keys.includes(key)) problems.push(`${path}${key} is not something that can be edited`);
|
|
210
|
+
};
|
|
211
|
+
allowed(input, [
|
|
212
|
+
"name",
|
|
213
|
+
"aliases",
|
|
214
|
+
"age",
|
|
215
|
+
"gender",
|
|
216
|
+
"pronouns",
|
|
217
|
+
"role",
|
|
218
|
+
"tier",
|
|
219
|
+
"kind",
|
|
220
|
+
"summary",
|
|
221
|
+
"personality",
|
|
222
|
+
"background",
|
|
223
|
+
"appearance",
|
|
224
|
+
"voice",
|
|
225
|
+
"visualIdentity",
|
|
226
|
+
"speech",
|
|
227
|
+
"state",
|
|
228
|
+
"place",
|
|
229
|
+
"goals"
|
|
230
|
+
], "");
|
|
231
|
+
const name = text(input, "name", "", NAME_LIMIT);
|
|
232
|
+
if (name !== void 0) {
|
|
233
|
+
if (name.trim() === "") problems.push("name cannot be blank");
|
|
234
|
+
else edit.name = name.trim();
|
|
235
|
+
}
|
|
236
|
+
const aliases = list(input, "aliases", "");
|
|
237
|
+
if (aliases !== void 0) edit.aliases = aliases;
|
|
238
|
+
for (const key of [
|
|
239
|
+
"age",
|
|
240
|
+
"gender",
|
|
241
|
+
"pronouns"
|
|
242
|
+
]) {
|
|
243
|
+
const found = text(input, key, "", NAME_LIMIT);
|
|
244
|
+
if (found !== void 0) edit[key] = found;
|
|
245
|
+
}
|
|
246
|
+
const voice = text(input, "voice", "", NAME_LIMIT);
|
|
247
|
+
if (voice !== void 0) edit.voice = voice;
|
|
248
|
+
for (const key of [
|
|
249
|
+
"summary",
|
|
250
|
+
"personality",
|
|
251
|
+
"background",
|
|
252
|
+
"appearance"
|
|
253
|
+
]) {
|
|
254
|
+
const found = text(input, key, "", TEXT_LIMIT);
|
|
255
|
+
if (found !== void 0) edit[key] = found;
|
|
256
|
+
}
|
|
257
|
+
const role = choice("role", CHARACTER_ROLES);
|
|
258
|
+
if (role !== void 0) edit.role = role;
|
|
259
|
+
const tier = choice("tier", CHARACTER_TIERS);
|
|
260
|
+
if (tier !== void 0) edit.tier = tier;
|
|
261
|
+
const kind = choice("kind", CHARACTER_KINDS);
|
|
262
|
+
if (kind !== void 0) edit.kind = kind;
|
|
263
|
+
const object = (key) => {
|
|
264
|
+
const found = input[key];
|
|
265
|
+
if (found === void 0) return void 0;
|
|
266
|
+
if (typeof found !== "object" || found === null || Array.isArray(found)) {
|
|
267
|
+
problems.push(`${key} must be an object`);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
return found;
|
|
271
|
+
};
|
|
272
|
+
if (input["visualIdentity"] === null) edit.visualIdentity = null;
|
|
273
|
+
else if (input["visualIdentity"] !== void 0) {
|
|
274
|
+
const visual = object("visualIdentity");
|
|
275
|
+
if (visual !== void 0) {
|
|
276
|
+
allowed(visual, [
|
|
277
|
+
"description",
|
|
278
|
+
"tags",
|
|
279
|
+
"negativeTags",
|
|
280
|
+
"globalId"
|
|
281
|
+
], "visualIdentity.");
|
|
282
|
+
const description = text(visual, "description", "visualIdentity.", 2e3);
|
|
283
|
+
const tags = list(visual, "tags", "visualIdentity.");
|
|
284
|
+
const negativeTags = list(visual, "negativeTags", "visualIdentity.");
|
|
285
|
+
const globalId = text(visual, "globalId", "visualIdentity.", NAME_LIMIT);
|
|
286
|
+
if (description === void 0 || description.trim() === "") problems.push("visualIdentity.description is needed");
|
|
287
|
+
else edit.visualIdentity = {
|
|
288
|
+
description: description.trim(),
|
|
289
|
+
tags: tags ?? [],
|
|
290
|
+
negativeTags: negativeTags ?? [],
|
|
291
|
+
...globalId === void 0 || globalId.trim() === "" ? {} : { globalId: globalId.trim() }
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
const speech = object("speech");
|
|
296
|
+
if (speech !== void 0) {
|
|
297
|
+
allowed(speech, ["style", "examples"], "speech.");
|
|
298
|
+
const style = text(speech, "style", "speech.", TEXT_LIMIT);
|
|
299
|
+
const examples = list(speech, "examples", "speech.");
|
|
300
|
+
edit.speech = {
|
|
301
|
+
...style === void 0 ? {} : { style },
|
|
302
|
+
...examples === void 0 ? {} : { examples }
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
const state = object("state");
|
|
306
|
+
if (state !== void 0) {
|
|
307
|
+
allowed(state, [
|
|
308
|
+
"publicState",
|
|
309
|
+
"innerState",
|
|
310
|
+
"activity"
|
|
311
|
+
], "state.");
|
|
312
|
+
edit.state = {};
|
|
313
|
+
for (const key of [
|
|
314
|
+
"publicState",
|
|
315
|
+
"innerState",
|
|
316
|
+
"activity"
|
|
317
|
+
]) {
|
|
318
|
+
const found = text(state, key, "state.", TEXT_LIMIT);
|
|
319
|
+
if (found !== void 0) edit.state[key] = found;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
const place = object("place");
|
|
323
|
+
if (place !== void 0) {
|
|
324
|
+
allowed(place, ["location", "position"], "place.");
|
|
325
|
+
const location = text(place, "location", "place.", NAME_LIMIT);
|
|
326
|
+
const position = text(place, "position", "place.", NAME_LIMIT);
|
|
327
|
+
if (location === void 0 || location.trim() === "") problems.push("place.location is needed");
|
|
328
|
+
else edit.place = {
|
|
329
|
+
location,
|
|
330
|
+
...position === void 0 ? {} : { position }
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
if (input["goals"] !== void 0) {
|
|
334
|
+
if (!Array.isArray(input["goals"])) problems.push("goals must be a list");
|
|
335
|
+
else {
|
|
336
|
+
const goals = [];
|
|
337
|
+
edit.goals = goals;
|
|
338
|
+
input["goals"].forEach((entry, index) => {
|
|
339
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
|
|
340
|
+
problems.push(`goals[${index}] must be an object`);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
const goal = entry;
|
|
344
|
+
const path = `goals[${index}].`;
|
|
345
|
+
allowed(goal, [
|
|
346
|
+
"ref",
|
|
347
|
+
"name",
|
|
348
|
+
"description",
|
|
349
|
+
"status",
|
|
350
|
+
"priority"
|
|
351
|
+
], path);
|
|
352
|
+
const ref = text(goal, "ref", path, NAME_LIMIT);
|
|
353
|
+
if (ref === void 0) {
|
|
354
|
+
problems.push(`${path}ref is needed`);
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
const goalName = text(goal, "name", path, NAME_LIMIT);
|
|
358
|
+
if (goalName !== void 0 && goalName.trim() === "") problems.push(`${path}name cannot be blank`);
|
|
359
|
+
const description = text(goal, "description", path, TEXT_LIMIT);
|
|
360
|
+
const status = choice("status", INTENT_STATUSES, goal, path);
|
|
361
|
+
const priority = goal["priority"];
|
|
362
|
+
if (priority !== void 0 && (typeof priority !== "number" || !Number.isFinite(priority) || priority < 0 || priority > 1)) problems.push(`${path}priority must be a number from 0 to 1`);
|
|
363
|
+
goals.push({
|
|
364
|
+
ref,
|
|
365
|
+
...goalName === void 0 ? {} : { name: goalName.trim() },
|
|
366
|
+
...description === void 0 ? {} : { description },
|
|
367
|
+
...status === void 0 ? {} : { status },
|
|
368
|
+
...typeof priority === "number" ? { priority } : {}
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
374
|
+
return edit;
|
|
375
|
+
}
|
|
376
|
+
function parseEntityEdit(value, kind) {
|
|
377
|
+
const problems = [];
|
|
378
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
|
|
379
|
+
const input = value;
|
|
380
|
+
const edit = {};
|
|
381
|
+
const allowed = kind === "place" ? [
|
|
382
|
+
"name",
|
|
383
|
+
"description",
|
|
384
|
+
"features",
|
|
385
|
+
"visualIdentity",
|
|
386
|
+
"parent"
|
|
387
|
+
] : [
|
|
388
|
+
"name",
|
|
389
|
+
"description",
|
|
390
|
+
"quantity",
|
|
391
|
+
"quality",
|
|
392
|
+
"notable",
|
|
393
|
+
"hidden",
|
|
394
|
+
"containerState",
|
|
395
|
+
"visualIdentity",
|
|
396
|
+
"owner"
|
|
397
|
+
];
|
|
398
|
+
const link = kind === "place" ? "parent" : "owner";
|
|
399
|
+
if (link in input) {
|
|
400
|
+
const target = input[link];
|
|
401
|
+
if (target === null) edit[link] = null;
|
|
402
|
+
else if (typeof target !== "string") problems.push(`${link} must be a key or null`);
|
|
403
|
+
else edit[link] = target.trim() === "" ? null : target.trim();
|
|
404
|
+
}
|
|
405
|
+
for (const key of Object.keys(input)) if (!allowed.includes(key)) problems.push(`${key} is not something that can be edited`);
|
|
406
|
+
for (const key of [
|
|
407
|
+
"name",
|
|
408
|
+
"description",
|
|
409
|
+
"quality"
|
|
410
|
+
]) {
|
|
411
|
+
if (!(key in input)) continue;
|
|
412
|
+
const value = input[key];
|
|
413
|
+
if (typeof value !== "string" || value.length > (key === "name" ? NAME_LIMIT : TEXT_LIMIT)) problems.push(`${key} must be text`);
|
|
414
|
+
else if (key === "name" && value.trim() === "") problems.push("name cannot be blank");
|
|
415
|
+
else edit[key] = key === "name" ? value.trim() : value;
|
|
416
|
+
}
|
|
417
|
+
for (const key of ["notable", "hidden"]) if (key in input) {
|
|
418
|
+
if (typeof input[key] !== "boolean") problems.push(`${key} must be true or false`);
|
|
419
|
+
else edit[key] = input[key];
|
|
420
|
+
}
|
|
421
|
+
if ("quantity" in input) {
|
|
422
|
+
const quantity = input["quantity"];
|
|
423
|
+
if (typeof quantity !== "number" || !Number.isInteger(quantity) || quantity < 1) problems.push("quantity must be a whole number from 1");
|
|
424
|
+
else edit["quantity"] = quantity;
|
|
425
|
+
}
|
|
426
|
+
if ("containerState" in input) {
|
|
427
|
+
const state = input["containerState"];
|
|
428
|
+
if (state !== "open" && state !== "closed" && state !== "locked") problems.push("containerState must be one of: open, closed, locked");
|
|
429
|
+
else edit["containerState"] = state;
|
|
430
|
+
}
|
|
431
|
+
if ("features" in input) {
|
|
432
|
+
const features = input["features"];
|
|
433
|
+
if (!Array.isArray(features) || features.length > 30 || !features.every((feature) => typeof feature === "object" && feature !== null && typeof feature["key"] === "string" && typeof feature["name"] === "string" && typeof feature["description"] === "string")) problems.push("features must be a list of named features");
|
|
434
|
+
else edit["features"] = features;
|
|
435
|
+
}
|
|
436
|
+
if (input["visualIdentity"] === null) edit["visualIdentity"] = null;
|
|
437
|
+
else if ("visualIdentity" in input) {
|
|
438
|
+
const identity = input["visualIdentity"];
|
|
439
|
+
if (typeof identity !== "object" || identity === null || Array.isArray(identity)) problems.push("visualIdentity must be an object");
|
|
440
|
+
else {
|
|
441
|
+
const visual = identity;
|
|
442
|
+
const description = visual["description"];
|
|
443
|
+
const tags = visual["tags"];
|
|
444
|
+
const negativeTags = visual["negativeTags"];
|
|
445
|
+
const globalId = visual["globalId"];
|
|
446
|
+
if (typeof description !== "string" || description.trim() === "") problems.push("visualIdentity.description is needed");
|
|
447
|
+
else if (!Array.isArray(tags) || !tags.every((value) => typeof value === "string") || !Array.isArray(negativeTags) || !negativeTags.every((value) => typeof value === "string") || globalId !== void 0 && typeof globalId !== "string") problems.push("visualIdentity has invalid fields");
|
|
448
|
+
else edit["visualIdentity"] = {
|
|
449
|
+
description: description.trim(),
|
|
450
|
+
tags,
|
|
451
|
+
negativeTags,
|
|
452
|
+
...globalId === void 0 || globalId.trim() === "" ? {} : { globalId: globalId.trim() }
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
457
|
+
return edit;
|
|
458
|
+
}
|
|
459
|
+
const parsePlaceEdit = (value) => parseEntityEdit(value, "place");
|
|
460
|
+
const parseThingEdit = (value) => parseEntityEdit(value, "thing");
|
|
461
|
+
function parseFactionEdit(value) {
|
|
462
|
+
const problems = [];
|
|
463
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
|
|
464
|
+
const input = value;
|
|
465
|
+
const allowed = [
|
|
466
|
+
"name",
|
|
467
|
+
"aliases",
|
|
468
|
+
"summary",
|
|
469
|
+
"description",
|
|
470
|
+
"values",
|
|
471
|
+
"structure",
|
|
472
|
+
"state",
|
|
473
|
+
"goals"
|
|
474
|
+
];
|
|
475
|
+
for (const key of Object.keys(input)) if (!allowed.includes(key)) problems.push(`${key} is not something that can be edited`);
|
|
476
|
+
const edit = {};
|
|
477
|
+
for (const key of [
|
|
478
|
+
"name",
|
|
479
|
+
"summary",
|
|
480
|
+
"description",
|
|
481
|
+
"structure"
|
|
482
|
+
]) if (key in input) {
|
|
483
|
+
const found = input[key];
|
|
484
|
+
if (typeof found !== "string" || found.length > TEXT_LIMIT) problems.push(`${key} must be text`);
|
|
485
|
+
else if (key === "name" && found.trim() === "") problems.push("name cannot be blank");
|
|
486
|
+
else edit[key] = key === "name" ? found.trim() : found;
|
|
487
|
+
}
|
|
488
|
+
for (const key of ["aliases", "values"]) if (key in input) {
|
|
489
|
+
const found = input[key];
|
|
490
|
+
if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= NAME_LIMIT)) problems.push(`${key} must be a list of short texts`);
|
|
491
|
+
else edit[key] = found;
|
|
492
|
+
}
|
|
493
|
+
if ("state" in input) {
|
|
494
|
+
const state = input["state"];
|
|
495
|
+
if (typeof state !== "object" || state === null || Array.isArray(state)) problems.push("state must be an object");
|
|
496
|
+
else {
|
|
497
|
+
const record = state;
|
|
498
|
+
edit.state = {};
|
|
499
|
+
for (const key of ["publicState", "innerState"]) if (key in record) {
|
|
500
|
+
if (typeof record[key] !== "string") problems.push(`state.${key} must be text`);
|
|
501
|
+
else edit.state[key] = record[key];
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
if ("goals" in input) try {
|
|
506
|
+
edit.goals = parseCharacterEdit({ goals: input["goals"] }).goals;
|
|
507
|
+
} catch (error) {
|
|
508
|
+
if (error instanceof InvalidEditProblems) problems.push(...error.problems);
|
|
509
|
+
else throw error;
|
|
510
|
+
}
|
|
511
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
512
|
+
return edit;
|
|
513
|
+
}
|
|
514
|
+
function parseLoreEdit(value) {
|
|
515
|
+
const problems = [];
|
|
516
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
|
|
517
|
+
const input = value;
|
|
518
|
+
const edit = {};
|
|
519
|
+
for (const key of Object.keys(input)) if (![
|
|
520
|
+
"title",
|
|
521
|
+
"kind",
|
|
522
|
+
"scope",
|
|
523
|
+
"knownBy",
|
|
524
|
+
"summary",
|
|
525
|
+
"body",
|
|
526
|
+
"startsAt",
|
|
527
|
+
"endsAt",
|
|
528
|
+
"sources"
|
|
529
|
+
].includes(key)) problems.push(`${key} is not something that can be edited`);
|
|
530
|
+
for (const key of [
|
|
531
|
+
"title",
|
|
532
|
+
"summary",
|
|
533
|
+
"body"
|
|
534
|
+
]) if (key in input) {
|
|
535
|
+
const found = input[key];
|
|
536
|
+
if (typeof found !== "string" || found.length > TEXT_LIMIT) problems.push(`${key} must be text`);
|
|
537
|
+
else if (key === "title" && found.trim() === "") problems.push("title cannot be blank");
|
|
538
|
+
else edit[key] = key === "title" ? found.trim() : found;
|
|
539
|
+
}
|
|
540
|
+
if ("kind" in input) {
|
|
541
|
+
if (typeof input["kind"] !== "string" || !LORE_KINDS.includes(input["kind"])) problems.push(`kind must be one of: ${LORE_KINDS.join(", ")}`);
|
|
542
|
+
else edit.kind = input["kind"];
|
|
543
|
+
}
|
|
544
|
+
if ("scope" in input) {
|
|
545
|
+
if (typeof input["scope"] !== "string" || !LORE_SCOPES.includes(input["scope"])) problems.push(`scope must be one of: ${LORE_SCOPES.join(", ")}`);
|
|
546
|
+
else edit.scope = input["scope"];
|
|
547
|
+
}
|
|
548
|
+
if ("knownBy" in input) {
|
|
549
|
+
const found = input["knownBy"];
|
|
550
|
+
if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.trim() !== "" && entry.length <= TEXT_LIMIT)) problems.push("knownBy must be a list of names");
|
|
551
|
+
else edit.knownBy = found.map((entry) => entry.trim());
|
|
552
|
+
}
|
|
553
|
+
if (edit.scope === "everyone" && (edit.knownBy?.length ?? 0) > 0) problems.push("an entry everyone knows has no list of who knows it");
|
|
554
|
+
for (const key of ["startsAt", "endsAt"]) if (key in input) {
|
|
555
|
+
const found = input[key];
|
|
556
|
+
if (found !== null && (typeof found !== "number" || !Number.isFinite(found))) problems.push(`${key} must be a timestamp or null`);
|
|
557
|
+
else edit[key] = found;
|
|
558
|
+
}
|
|
559
|
+
if ("sources" in input) {
|
|
560
|
+
const found = input["sources"];
|
|
561
|
+
if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= TEXT_LIMIT)) problems.push("sources must be a list of texts");
|
|
562
|
+
else edit.sources = found;
|
|
563
|
+
}
|
|
564
|
+
const starts = edit.startsAt === null ? void 0 : edit.startsAt;
|
|
565
|
+
const ends = edit.endsAt === null ? void 0 : edit.endsAt;
|
|
566
|
+
if (starts !== void 0 && ends !== void 0 && ends < starts) problems.push("endsAt must not be before startsAt");
|
|
567
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
568
|
+
return edit;
|
|
569
|
+
}
|
|
570
|
+
function parseRelationEdit(value) {
|
|
571
|
+
const problems = [];
|
|
572
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
|
|
573
|
+
const input = value;
|
|
574
|
+
const kind = input["kind"];
|
|
575
|
+
const key = input["key"];
|
|
576
|
+
if (![
|
|
577
|
+
"character",
|
|
578
|
+
"knowledge",
|
|
579
|
+
"membership",
|
|
580
|
+
"social",
|
|
581
|
+
"exit"
|
|
582
|
+
].includes(String(kind))) problems.push("kind is not a relation kind");
|
|
583
|
+
const creating = input["create"] === true;
|
|
584
|
+
if (!creating && (typeof key !== "string" || key.trim() === "" || key.length > 500)) problems.push("key is needed");
|
|
585
|
+
if (!creating && typeof key === "string" && key.trim() !== "" && typeof input["from"] === "string" && typeof input["to"] === "string" && input["remove"] !== true) problems.push("to make a new relationship send create: true with from and to and no key; a key names one that exists, exactly as list_relationships shows it");
|
|
586
|
+
if ("create" in input && typeof input["create"] !== "boolean") problems.push("create must be true or false");
|
|
587
|
+
const allowedByKind = {
|
|
588
|
+
character: [
|
|
589
|
+
"kind",
|
|
590
|
+
"key",
|
|
591
|
+
"create",
|
|
592
|
+
"from",
|
|
593
|
+
"to",
|
|
594
|
+
"remove",
|
|
595
|
+
"label",
|
|
596
|
+
"summary",
|
|
597
|
+
"familiarity",
|
|
598
|
+
"trust",
|
|
599
|
+
"affinity",
|
|
600
|
+
"tension"
|
|
601
|
+
],
|
|
602
|
+
knowledge: [
|
|
603
|
+
"kind",
|
|
604
|
+
"key",
|
|
605
|
+
"create",
|
|
606
|
+
"from",
|
|
607
|
+
"toKind",
|
|
608
|
+
"to",
|
|
609
|
+
"observed",
|
|
610
|
+
"remove"
|
|
611
|
+
],
|
|
612
|
+
membership: [
|
|
613
|
+
"kind",
|
|
614
|
+
"key",
|
|
615
|
+
"create",
|
|
616
|
+
"from",
|
|
617
|
+
"to",
|
|
618
|
+
"remove",
|
|
619
|
+
"role",
|
|
620
|
+
"rank",
|
|
621
|
+
"status",
|
|
622
|
+
"public",
|
|
623
|
+
"commitment"
|
|
624
|
+
],
|
|
625
|
+
social: [
|
|
626
|
+
"kind",
|
|
627
|
+
"key",
|
|
628
|
+
"create",
|
|
629
|
+
"fromKind",
|
|
630
|
+
"from",
|
|
631
|
+
"toKind",
|
|
632
|
+
"to",
|
|
633
|
+
"remove",
|
|
634
|
+
"label",
|
|
635
|
+
"summary",
|
|
636
|
+
"familiarity",
|
|
637
|
+
"trust",
|
|
638
|
+
"affinity",
|
|
639
|
+
"tension"
|
|
640
|
+
],
|
|
641
|
+
exit: [
|
|
642
|
+
"kind",
|
|
643
|
+
"key",
|
|
644
|
+
"create",
|
|
645
|
+
"from",
|
|
646
|
+
"to",
|
|
647
|
+
"remove",
|
|
648
|
+
"description",
|
|
649
|
+
"travelSeconds",
|
|
650
|
+
"state",
|
|
651
|
+
"note"
|
|
652
|
+
]
|
|
653
|
+
};
|
|
654
|
+
for (const field of Object.keys(input)) if (!(allowedByKind[String(kind)] ?? []).includes(field)) problems.push(`${field} is not something that can be edited`);
|
|
655
|
+
if ("remove" in input && typeof input["remove"] !== "boolean") problems.push("remove must be true or false");
|
|
656
|
+
for (const field of [
|
|
657
|
+
"label",
|
|
658
|
+
"summary",
|
|
659
|
+
"role",
|
|
660
|
+
"rank",
|
|
661
|
+
"description",
|
|
662
|
+
"note"
|
|
663
|
+
]) if (field in input && (typeof input[field] !== "string" || input[field].length > TEXT_LIMIT)) problems.push(`${field} must be text`);
|
|
664
|
+
for (const field of [
|
|
665
|
+
"familiarity",
|
|
666
|
+
"trust",
|
|
667
|
+
"affinity",
|
|
668
|
+
"tension",
|
|
669
|
+
"commitment"
|
|
670
|
+
]) if (field in input) {
|
|
671
|
+
const number = input[field];
|
|
672
|
+
const signed = field === "trust" || field === "affinity";
|
|
673
|
+
if (typeof number !== "number" || !Number.isFinite(number) || number < (signed ? -1 : 0) || number > 1) problems.push(`${field} must be between ${signed ? "-1" : "0"} and 1`);
|
|
674
|
+
}
|
|
675
|
+
if ("travelSeconds" in input && input["travelSeconds"] !== null && (typeof input["travelSeconds"] !== "number" || !Number.isInteger(input["travelSeconds"]) || input["travelSeconds"] < 0)) problems.push("travelSeconds must be a non-negative whole number or null");
|
|
676
|
+
if ("public" in input && typeof input["public"] !== "boolean") problems.push("public must be true or false");
|
|
677
|
+
if ("observed" in input && typeof input["observed"] !== "boolean") problems.push("observed must be true or false");
|
|
678
|
+
if ("status" in input) {
|
|
679
|
+
const choices = kind === "exit" ? EXIT_STATES : MEMBERSHIP_STATUSES;
|
|
680
|
+
if (typeof input["status"] !== "string" || !choices.includes(input["status"])) problems.push(`status must be one of: ${choices.join(", ")}`);
|
|
681
|
+
}
|
|
682
|
+
if (creating) {
|
|
683
|
+
for (const field of ["from", "to"]) if (typeof input[field] !== "string" || input[field].trim() === "") problems.push(`${field} is needed`);
|
|
684
|
+
if ((kind === "character" || kind === "social") && (typeof input["label"] !== "string" || input["label"].trim() === "")) problems.push("label is needed");
|
|
685
|
+
if (kind === "membership" && (typeof input["role"] !== "string" || input["role"].trim() === "")) problems.push("role is needed");
|
|
686
|
+
if (kind === "exit" && typeof input["description"] !== "string") problems.push("description is needed");
|
|
687
|
+
if (kind === "knowledge" && ![
|
|
688
|
+
"location",
|
|
689
|
+
"item",
|
|
690
|
+
"exit"
|
|
691
|
+
].includes(String(input["toKind"]))) problems.push("toKind must be one of: location, item, exit");
|
|
692
|
+
if (kind === "social") {
|
|
693
|
+
for (const field of ["fromKind", "toKind"]) if (!["character", "faction"].includes(String(input[field]))) problems.push(`${field} must be character or faction`);
|
|
694
|
+
}
|
|
695
|
+
} else if (kind === "knowledge" && input["remove"] !== true) problems.push("knowledge editing supports creation or removal");
|
|
696
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
697
|
+
return input;
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* Read an `id` field. Ids are opaque strings, unique within their scope, that
|
|
701
|
+
* stay the same when the file is copied or edited.
|
|
702
|
+
* @param fallback - used when the file sets none.
|
|
703
|
+
*/
|
|
704
|
+
function readIdentifier(reader, fallback) {
|
|
705
|
+
const id = reader.string("id") ?? fallback;
|
|
706
|
+
if (id !== void 0 && id.length > 100) reader.fail("id", `must be at most 100 characters`);
|
|
707
|
+
return id;
|
|
708
|
+
}
|
|
709
|
+
//#endregion
|
|
710
|
+
//#region src/host/variables/values.ts
|
|
711
|
+
/** At most this many initial values in one file. */
|
|
712
|
+
const MAX_VALUES = 40;
|
|
713
|
+
/** The `variables` of a world file: what a character, item, place or the world starts with, by the key of each variable. */
|
|
714
|
+
function readVariableValues(reader) {
|
|
715
|
+
const value = reader.raw("variables");
|
|
716
|
+
if (value === void 0 || value === null) return void 0;
|
|
717
|
+
if (typeof value !== "object" || Array.isArray(value)) {
|
|
718
|
+
reader.fail("variables", "must be an object of values by variable key");
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
const entries = Object.entries(value);
|
|
722
|
+
if (entries.length > MAX_VALUES) reader.fail("variables", `at most ${MAX_VALUES} values`);
|
|
723
|
+
const values = {};
|
|
724
|
+
for (const [key, entry] of entries) if (typeof entry === "number" && Number.isFinite(entry) || typeof entry === "boolean" || typeof entry === "string") values[key] = entry;
|
|
725
|
+
else reader.fail(`variables.${key}`, "must be a number, true or false, or text");
|
|
726
|
+
return values;
|
|
727
|
+
}
|
|
728
|
+
const MAX_VISUAL_DESCRIPTION = 2e3;
|
|
729
|
+
/** Read an optional provider-neutral visual identity from an authored entity file. */
|
|
730
|
+
function readVisualIdentity(reader) {
|
|
731
|
+
const visual = reader.object("visual_identity");
|
|
732
|
+
if (visual === void 0) return void 0;
|
|
733
|
+
const description = visual.string("description", { required: true });
|
|
734
|
+
const tags = visual.strings("tags");
|
|
735
|
+
const negativeTags = visual.strings("negative_tags");
|
|
736
|
+
const globalId = visual.string("global_id");
|
|
737
|
+
if (description !== void 0 && description.length > 2e3) visual.fail("description", `must be at most ${MAX_VISUAL_DESCRIPTION} characters`);
|
|
738
|
+
if (tags.length > 40) visual.fail("tags", `has at most 40 entries`);
|
|
739
|
+
if (negativeTags.length > 40) visual.fail("negative_tags", `has at most 40 entries`);
|
|
740
|
+
if (description === void 0) return void 0;
|
|
741
|
+
return {
|
|
742
|
+
description,
|
|
743
|
+
tags,
|
|
744
|
+
negativeTags,
|
|
745
|
+
...globalId === void 0 ? {} : { globalId }
|
|
746
|
+
};
|
|
747
|
+
}
|
|
748
|
+
//#endregion
|
|
749
|
+
//#region src/host/characters/character-file.ts
|
|
750
|
+
const CHARACTER_FILE_NAME = "character.json";
|
|
751
|
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}/;
|
|
752
|
+
function readAge(reader) {
|
|
753
|
+
const value = reader.raw("age");
|
|
754
|
+
if (typeof value === "number") {
|
|
755
|
+
if (Number.isFinite(value) && value >= 0) return String(value);
|
|
756
|
+
} else if (value === void 0 || typeof value === "string") return reader.string("age");
|
|
757
|
+
reader.fail("age", "must be a string or a non-negative number");
|
|
758
|
+
}
|
|
759
|
+
function readVector(reader) {
|
|
760
|
+
const axis = (key) => reader.number(key, {
|
|
761
|
+
min: -1,
|
|
762
|
+
max: 1
|
|
763
|
+
}) ?? 0;
|
|
764
|
+
return {
|
|
765
|
+
valence: axis("valence"),
|
|
766
|
+
arousal: axis("arousal"),
|
|
767
|
+
dominance: axis("dominance")
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
function readEmotion(reader) {
|
|
771
|
+
if (reader === void 0) return void 0;
|
|
772
|
+
const baselineReader = reader.object("baseline");
|
|
773
|
+
if (baselineReader === void 0) {
|
|
774
|
+
reader.fail("baseline", "is required");
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
const baseline = readVector(baselineReader);
|
|
778
|
+
const immediateReader = reader.object("immediate");
|
|
779
|
+
return {
|
|
780
|
+
baseline,
|
|
781
|
+
immediate: immediateReader === void 0 ? { ...baseline } : readVector(immediateReader)
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
function readIntent(reader) {
|
|
785
|
+
const name = reader.string("name", { required: true });
|
|
786
|
+
const deadline = reader.string("deadline");
|
|
787
|
+
const deadlineTime = deadline === void 0 ? void 0 : ISO_DATE.test(deadline) ? Date.parse(deadline) : NaN;
|
|
788
|
+
if (deadline !== void 0 && Number.isNaN(deadlineTime)) reader.fail("deadline", "must be an ISO 8601 date-time");
|
|
789
|
+
const intent = {
|
|
790
|
+
type: reader.oneOf("type", INTENT_TYPES, "agenda"),
|
|
791
|
+
description: reader.text("description"),
|
|
792
|
+
status: reader.oneOf("status", INTENT_STATUSES, "active"),
|
|
793
|
+
horizon: reader.oneOf("horizon", INTENT_HORIZONS, "short"),
|
|
794
|
+
priority: reader.number("priority", {
|
|
795
|
+
min: 0,
|
|
796
|
+
max: 1
|
|
797
|
+
}) ?? .5,
|
|
798
|
+
urgency: reader.number("urgency", {
|
|
799
|
+
min: 0,
|
|
800
|
+
max: 1
|
|
801
|
+
}) ?? .5,
|
|
802
|
+
plan: reader.strings("plan"),
|
|
803
|
+
openThreads: reader.strings("open_threads"),
|
|
804
|
+
constraints: reader.strings("constraints"),
|
|
805
|
+
...deadlineTime === void 0 || Number.isNaN(deadlineTime) ? {} : { deadline: new Date(deadlineTime).toISOString() }
|
|
806
|
+
};
|
|
807
|
+
return name === void 0 ? void 0 : {
|
|
808
|
+
...intent,
|
|
809
|
+
name
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
const TIME_OF_DAY = /^([01]?\d|2[0-3]):[0-5]\d$/;
|
|
813
|
+
function readRoutine(reader) {
|
|
814
|
+
const windows = reader.objects("routine").flatMap((window) => {
|
|
815
|
+
const from = window.string("from", { required: true });
|
|
816
|
+
const to = window.string("to", { required: true });
|
|
817
|
+
for (const [key, value] of [["from", from], ["to", to]]) if (value !== void 0 && !TIME_OF_DAY.test(value)) window.fail(key, `"${value}" is not a time of day: write it as 07:30 (24-hour)`);
|
|
818
|
+
if (from !== void 0 && from === to) window.fail("to", "a window that ends when it starts is empty");
|
|
819
|
+
const activity = window.string("activity", { required: true });
|
|
820
|
+
const days = window.strings("days").map((day) => day.toLowerCase());
|
|
821
|
+
const on = window.strings("on");
|
|
822
|
+
for (const problem of dayTokenProblems(on, "on", "any")) window.fail("on", problem.replace(/^on: /, ""));
|
|
823
|
+
for (const day of days) if (!WEEKDAY_NAMES.includes(day)) window.fail("days", `"${day}" is not a day (${WEEKDAY_NAMES.join(", ")})`);
|
|
824
|
+
const location = window.string("location");
|
|
825
|
+
const feature = window.string("feature");
|
|
826
|
+
const position = window.string("position");
|
|
827
|
+
if (location === void 0 && feature !== void 0) window.fail("feature", "needs a location");
|
|
828
|
+
const flag = window.raw("interruptible");
|
|
829
|
+
if (flag !== void 0 && typeof flag !== "boolean") window.fail("interruptible", "must be true or false");
|
|
830
|
+
if (from === void 0 || to === void 0 || activity === void 0) return [];
|
|
831
|
+
return [{
|
|
832
|
+
days,
|
|
833
|
+
...on.length === 0 ? {} : { on },
|
|
834
|
+
from,
|
|
835
|
+
to,
|
|
836
|
+
activity,
|
|
837
|
+
...location === void 0 ? {} : { location },
|
|
838
|
+
...feature === void 0 ? {} : { feature },
|
|
839
|
+
...position === void 0 ? {} : { position },
|
|
840
|
+
interruptible: flag !== false
|
|
841
|
+
}];
|
|
842
|
+
});
|
|
843
|
+
if (windows.length > MAX_ROUTINE_WINDOWS) reader.fail("routine", `a character has at most ${MAX_ROUTINE_WINDOWS} windows in its day`);
|
|
844
|
+
return windows;
|
|
845
|
+
}
|
|
846
|
+
function readKnowledge(reader) {
|
|
847
|
+
if (reader === void 0) return void 0;
|
|
848
|
+
const exits = reader.objects("exits").flatMap((exit) => {
|
|
849
|
+
const from = exit.string("from", { required: true });
|
|
850
|
+
const to = exit.string("to", { required: true });
|
|
851
|
+
return from === void 0 || to === void 0 ? [] : [{
|
|
852
|
+
from,
|
|
853
|
+
to
|
|
854
|
+
}];
|
|
855
|
+
});
|
|
856
|
+
return {
|
|
857
|
+
locations: reader.strings("locations"),
|
|
858
|
+
items: reader.strings("items"),
|
|
859
|
+
exits,
|
|
860
|
+
lore: reader.strings("lore")
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
function readRelationships$1(reader) {
|
|
864
|
+
const seen = /* @__PURE__ */ new Set();
|
|
865
|
+
const relationships = reader.objects("relationships").flatMap((relation) => {
|
|
866
|
+
const to = relation.string("to", { required: true });
|
|
867
|
+
const label = relation.string("label", { required: true });
|
|
868
|
+
const familiarity = relation.number("familiarity", {
|
|
869
|
+
min: 0,
|
|
870
|
+
max: 1
|
|
871
|
+
}) ?? 0;
|
|
872
|
+
const trust = relation.number("trust", {
|
|
873
|
+
min: -1,
|
|
874
|
+
max: 1
|
|
875
|
+
}) ?? 0;
|
|
876
|
+
const affinity = relation.number("affinity", {
|
|
877
|
+
min: -1,
|
|
878
|
+
max: 1
|
|
879
|
+
}) ?? 0;
|
|
880
|
+
const tension = relation.number("tension", {
|
|
881
|
+
min: 0,
|
|
882
|
+
max: 1
|
|
883
|
+
}) ?? 0;
|
|
884
|
+
if (to !== void 0 && seen.has(to)) relation.fail("to", `"${to}" is listed twice: one profile per character`);
|
|
885
|
+
if (to !== void 0) seen.add(to);
|
|
886
|
+
return to === void 0 || label === void 0 ? [] : [{
|
|
887
|
+
to,
|
|
888
|
+
label,
|
|
889
|
+
summary: relation.text("summary"),
|
|
890
|
+
familiarity,
|
|
891
|
+
trust,
|
|
892
|
+
affinity,
|
|
893
|
+
tension
|
|
894
|
+
}];
|
|
895
|
+
});
|
|
896
|
+
if (relationships.length > 60) reader.fail("relationships", `a character has at most 60 relationship profiles`);
|
|
897
|
+
return relationships;
|
|
898
|
+
}
|
|
899
|
+
function readStart(reader) {
|
|
900
|
+
const emotion = readEmotion(reader?.object("emotion"));
|
|
901
|
+
const location = reader?.string("location");
|
|
902
|
+
const position = reader?.string("position");
|
|
903
|
+
const feature = reader?.string("feature");
|
|
904
|
+
if (location === void 0 && (position !== void 0 || feature !== void 0)) reader?.fail(position === void 0 ? "feature" : "position", "needs a location");
|
|
905
|
+
return {
|
|
906
|
+
publicState: reader?.text("public_state") ?? "",
|
|
907
|
+
innerState: reader?.text("inner_state") ?? "",
|
|
908
|
+
activity: reader?.text("activity") ?? "",
|
|
909
|
+
...emotion === void 0 ? {} : { emotion },
|
|
910
|
+
intents: reader?.objects("intents").flatMap((intent) => readIntent(intent) ?? []) ?? [],
|
|
911
|
+
...location === void 0 ? {} : { place: {
|
|
912
|
+
location,
|
|
913
|
+
...position === void 0 ? {} : { position },
|
|
914
|
+
...feature === void 0 ? {} : { feature }
|
|
915
|
+
} }
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Read a `character.json` into the canonical character definition.
|
|
920
|
+
* @param fallbackId - used when the file sets no `id`; the name of its folder.
|
|
921
|
+
*/
|
|
922
|
+
function parseCharacterFile(text, fallbackId) {
|
|
923
|
+
const issues = [];
|
|
924
|
+
const reader = Reader.fromJson(text, issues);
|
|
925
|
+
if (reader === void 0) return {
|
|
926
|
+
ok: false,
|
|
927
|
+
issues
|
|
928
|
+
};
|
|
929
|
+
const id = readIdentifier(reader, fallbackId) ?? fallbackId;
|
|
930
|
+
const name = reader.string("name", { required: true });
|
|
931
|
+
const kind = reader.oneOf("kind", CHARACTER_KINDS, "person");
|
|
932
|
+
const tier = reader.oneOf("tier", CHARACTER_TIERS, "principal");
|
|
933
|
+
const role = reader.oneOf("role", CHARACTER_ROLES, "npc");
|
|
934
|
+
if (role === "playable") {
|
|
935
|
+
if (kind === "group") reader.fail("role", "a playable character must be a person");
|
|
936
|
+
if (tier === "background") reader.fail("role", "a playable character cannot be a background character");
|
|
937
|
+
}
|
|
938
|
+
const age = readAge(reader);
|
|
939
|
+
const gender = reader.string("gender");
|
|
940
|
+
const pronouns = reader.string("pronouns");
|
|
941
|
+
const voice = reader.string("voice");
|
|
942
|
+
const speech = reader.object("speech");
|
|
943
|
+
const variables = readVariableValues(reader);
|
|
944
|
+
const visualIdentity = readVisualIdentity(reader);
|
|
945
|
+
const knowledge = readKnowledge(reader.object("knowledge"));
|
|
946
|
+
const character = {
|
|
947
|
+
id,
|
|
948
|
+
name: name ?? "",
|
|
949
|
+
aliases: reader.strings("aliases").filter((alias) => alias.toLowerCase() !== name?.toLowerCase()),
|
|
950
|
+
...age === void 0 ? {} : { age },
|
|
951
|
+
...gender === void 0 ? {} : { gender },
|
|
952
|
+
...pronouns === void 0 ? {} : { pronouns },
|
|
953
|
+
...voice === void 0 ? {} : { voice },
|
|
954
|
+
kind,
|
|
955
|
+
tier,
|
|
956
|
+
role,
|
|
957
|
+
summary: reader.text("summary"),
|
|
958
|
+
personality: reader.text("personality"),
|
|
959
|
+
background: reader.text("background"),
|
|
960
|
+
appearance: reader.text("appearance"),
|
|
961
|
+
...visualIdentity === void 0 ? {} : { visualIdentity },
|
|
962
|
+
speech: {
|
|
963
|
+
style: speech?.text("style") ?? "",
|
|
964
|
+
examples: speech?.strings("examples") ?? []
|
|
965
|
+
},
|
|
966
|
+
start: readStart(reader.object("start")),
|
|
967
|
+
...reader.raw("relationships") === void 0 ? {} : { relationships: readRelationships$1(reader) },
|
|
968
|
+
...knowledge === void 0 ? {} : { knowledge },
|
|
969
|
+
...reader.raw("routine") === void 0 ? {} : { routine: readRoutine(reader) },
|
|
970
|
+
...variables === void 0 ? {} : { variables }
|
|
971
|
+
};
|
|
972
|
+
return issues.length > 0 ? {
|
|
973
|
+
ok: false,
|
|
974
|
+
issues
|
|
975
|
+
} : {
|
|
976
|
+
ok: true,
|
|
977
|
+
value: character
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
//#endregion
|
|
981
|
+
//#region src/host/factions/faction-file.ts
|
|
982
|
+
const FACTION_FILE_NAME = "faction.json";
|
|
983
|
+
function readMembers(reader) {
|
|
984
|
+
const seen = /* @__PURE__ */ new Set();
|
|
985
|
+
const members = reader.objects("members").flatMap((entry) => {
|
|
986
|
+
const character = entry.string("character", { required: true });
|
|
987
|
+
if (character !== void 0 && seen.has(character)) entry.fail("character", `"${character}" is listed twice`);
|
|
988
|
+
if (character !== void 0) seen.add(character);
|
|
989
|
+
const visibility = entry.raw("public");
|
|
990
|
+
if (visibility !== void 0 && typeof visibility !== "boolean") entry.fail("public", "must be true or false");
|
|
991
|
+
const commitment = entry.number("commitment", {
|
|
992
|
+
min: 0,
|
|
993
|
+
max: 1
|
|
994
|
+
}) ?? .5;
|
|
995
|
+
return character === void 0 ? [] : [{
|
|
996
|
+
character,
|
|
997
|
+
role: entry.text("role"),
|
|
998
|
+
rank: entry.text("rank"),
|
|
999
|
+
status: entry.oneOf("status", MEMBERSHIP_STATUSES, "active"),
|
|
1000
|
+
public: visibility !== false,
|
|
1001
|
+
commitment
|
|
1002
|
+
}];
|
|
1003
|
+
});
|
|
1004
|
+
if (members.length > 500) reader.fail("members", `a faction has at most 500 authored members`);
|
|
1005
|
+
return members;
|
|
1006
|
+
}
|
|
1007
|
+
function readRelationships(reader) {
|
|
1008
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1009
|
+
const relationships = reader.objects("relationships").flatMap((entry) => {
|
|
1010
|
+
const target = entry.object("to");
|
|
1011
|
+
if (target === void 0) entry.fail("to", "is required");
|
|
1012
|
+
const kind = target?.oneOf("kind", ["character", "faction"], "faction");
|
|
1013
|
+
const id = target?.string("id", { required: true });
|
|
1014
|
+
const label = entry.string("label", { required: true });
|
|
1015
|
+
const key = `${kind}:${id}`;
|
|
1016
|
+
if (kind !== void 0 && id !== void 0 && seen.has(key)) target?.fail("id", "is listed twice from this faction");
|
|
1017
|
+
if (kind !== void 0 && id !== void 0) seen.add(key);
|
|
1018
|
+
if (kind === void 0 || id === void 0 || label === void 0) return [];
|
|
1019
|
+
return [{
|
|
1020
|
+
to: {
|
|
1021
|
+
kind,
|
|
1022
|
+
id
|
|
1023
|
+
},
|
|
1024
|
+
label,
|
|
1025
|
+
summary: entry.text("summary"),
|
|
1026
|
+
familiarity: entry.number("familiarity", {
|
|
1027
|
+
min: 0,
|
|
1028
|
+
max: 1
|
|
1029
|
+
}) ?? 0,
|
|
1030
|
+
trust: entry.number("trust", {
|
|
1031
|
+
min: -1,
|
|
1032
|
+
max: 1
|
|
1033
|
+
}) ?? 0,
|
|
1034
|
+
affinity: entry.number("affinity", {
|
|
1035
|
+
min: -1,
|
|
1036
|
+
max: 1
|
|
1037
|
+
}) ?? 0,
|
|
1038
|
+
tension: entry.number("tension", {
|
|
1039
|
+
min: 0,
|
|
1040
|
+
max: 1
|
|
1041
|
+
}) ?? 0
|
|
1042
|
+
}];
|
|
1043
|
+
});
|
|
1044
|
+
if (relationships.length > 100) reader.fail("relationships", `a faction has at most 100 relationship profiles`);
|
|
1045
|
+
return relationships;
|
|
1046
|
+
}
|
|
1047
|
+
function parseFactionFile(text, fallbackId) {
|
|
1048
|
+
const issues = [];
|
|
1049
|
+
const reader = Reader.fromJson(text, issues);
|
|
1050
|
+
if (reader === void 0) return {
|
|
1051
|
+
ok: false,
|
|
1052
|
+
issues
|
|
1053
|
+
};
|
|
1054
|
+
const start = reader.object("start");
|
|
1055
|
+
const id = readIdentifier(reader, fallbackId) ?? fallbackId;
|
|
1056
|
+
const name = reader.string("name", { required: true });
|
|
1057
|
+
const faction = {
|
|
1058
|
+
id,
|
|
1059
|
+
name: name ?? "",
|
|
1060
|
+
aliases: reader.strings("aliases").filter((alias) => alias.toLowerCase() !== name?.toLowerCase()),
|
|
1061
|
+
summary: reader.text("summary"),
|
|
1062
|
+
description: reader.text("description"),
|
|
1063
|
+
values: reader.strings("values"),
|
|
1064
|
+
structure: reader.text("structure"),
|
|
1065
|
+
start: {
|
|
1066
|
+
publicState: start?.text("public_state") ?? "",
|
|
1067
|
+
innerState: start?.text("inner_state") ?? "",
|
|
1068
|
+
goals: start?.objects("goals").flatMap((goal) => readIntent(goal) ?? []) ?? []
|
|
1069
|
+
},
|
|
1070
|
+
members: readMembers(reader),
|
|
1071
|
+
relationships: readRelationships(reader)
|
|
1072
|
+
};
|
|
1073
|
+
return issues.length === 0 ? {
|
|
1074
|
+
ok: true,
|
|
1075
|
+
value: faction
|
|
1076
|
+
} : {
|
|
1077
|
+
ok: false,
|
|
1078
|
+
issues
|
|
1079
|
+
};
|
|
1080
|
+
}
|
|
1081
|
+
//#endregion
|
|
1082
|
+
//#region src/host/items/item-file.ts
|
|
1083
|
+
const ITEM_FILE_NAME = "item.json";
|
|
1084
|
+
const SLOTS_FILE_NAME = "slots.json";
|
|
1085
|
+
/** Read an `item.json`; `fallbackId` (the folder name) is its id when the file sets none. */
|
|
1086
|
+
function parseItemFile(text, fallbackId) {
|
|
1087
|
+
const issues = [];
|
|
1088
|
+
const reader = Reader.fromJson(text, issues);
|
|
1089
|
+
if (reader === void 0) return {
|
|
1090
|
+
ok: false,
|
|
1091
|
+
issues
|
|
1092
|
+
};
|
|
1093
|
+
const id = readIdentifier(reader, fallbackId) ?? fallbackId;
|
|
1094
|
+
const name = reader.string("name", { required: true });
|
|
1095
|
+
const quantity = reader.number("quantity", { min: 1 }) ?? 1;
|
|
1096
|
+
if (!Number.isInteger(quantity)) reader.fail("quantity", "must be a whole number");
|
|
1097
|
+
const flag = (key) => {
|
|
1098
|
+
const value = reader.raw(key);
|
|
1099
|
+
if (value !== void 0 && typeof value !== "boolean") reader.fail(key, "must be true or false");
|
|
1100
|
+
return value === true;
|
|
1101
|
+
};
|
|
1102
|
+
const unique = flag("unique");
|
|
1103
|
+
if (unique && quantity > 1) reader.fail("unique", "a unique item is one thing: leave the quantity out");
|
|
1104
|
+
const wearable = reader.string("wearable");
|
|
1105
|
+
if (wearable !== void 0 && !SLOT_ID.test(wearable)) reader.fail("wearable", "must be the id of a slot: lowercase letters, digits, \"-\" or \"_\"");
|
|
1106
|
+
const box = reader.object("container");
|
|
1107
|
+
const container = box === void 0 ? void 0 : {
|
|
1108
|
+
state: box.oneOf("state", CONTAINER_STATES, "closed"),
|
|
1109
|
+
openedBy: box.strings("opened_by")
|
|
1110
|
+
};
|
|
1111
|
+
if (container !== void 0 && container.openedBy.length > 10) box?.fail("opened_by", `at most 10 items open one lock`);
|
|
1112
|
+
const owner = reader.string("owner");
|
|
1113
|
+
const location = reader.string("location");
|
|
1114
|
+
const heldBy = reader.string("held_by");
|
|
1115
|
+
const wornBy = reader.string("worn_by");
|
|
1116
|
+
const inside = reader.string("inside");
|
|
1117
|
+
const position = reader.string("position");
|
|
1118
|
+
const feature = reader.string("feature");
|
|
1119
|
+
const holders = [
|
|
1120
|
+
location,
|
|
1121
|
+
heldBy,
|
|
1122
|
+
wornBy,
|
|
1123
|
+
inside
|
|
1124
|
+
].filter((holder) => holder !== void 0).length;
|
|
1125
|
+
if (holders !== 1) reader.fail(holders === 0 ? "location" : "held_by", "say where it starts with exactly one of location, held_by, worn_by or inside");
|
|
1126
|
+
if (feature !== void 0 && location === void 0) reader.fail("feature", "needs a location");
|
|
1127
|
+
if (wornBy !== void 0 && wearable === void 0) reader.fail("worn_by", "it is worn but not wearable: give it a wearable slot");
|
|
1128
|
+
const start = location !== void 0 ? {
|
|
1129
|
+
kind: "location",
|
|
1130
|
+
location,
|
|
1131
|
+
...position === void 0 ? {} : { position },
|
|
1132
|
+
...feature === void 0 ? {} : { feature }
|
|
1133
|
+
} : heldBy !== void 0 ? {
|
|
1134
|
+
kind: "held",
|
|
1135
|
+
character: heldBy
|
|
1136
|
+
} : wornBy !== void 0 ? {
|
|
1137
|
+
kind: "worn",
|
|
1138
|
+
character: wornBy,
|
|
1139
|
+
...position === void 0 ? {} : { position }
|
|
1140
|
+
} : {
|
|
1141
|
+
kind: "inside",
|
|
1142
|
+
item: inside ?? "",
|
|
1143
|
+
...position === void 0 ? {} : { position }
|
|
1144
|
+
};
|
|
1145
|
+
const variables = readVariableValues(reader);
|
|
1146
|
+
const visualIdentity = readVisualIdentity(reader);
|
|
1147
|
+
const definition = {
|
|
1148
|
+
id,
|
|
1149
|
+
name: name ?? "",
|
|
1150
|
+
description: reader.text("description"),
|
|
1151
|
+
...visualIdentity === void 0 ? {} : { visualIdentity },
|
|
1152
|
+
quantity,
|
|
1153
|
+
unique,
|
|
1154
|
+
quality: reader.text("quality"),
|
|
1155
|
+
notable: flag("notable"),
|
|
1156
|
+
hidden: flag("hidden"),
|
|
1157
|
+
...wearable === void 0 ? {} : { wearable },
|
|
1158
|
+
...container === void 0 ? {} : { container },
|
|
1159
|
+
...owner === void 0 ? {} : { owner },
|
|
1160
|
+
...variables === void 0 ? {} : { variables },
|
|
1161
|
+
start
|
|
1162
|
+
};
|
|
1163
|
+
return issues.length > 0 ? {
|
|
1164
|
+
ok: false,
|
|
1165
|
+
issues
|
|
1166
|
+
} : {
|
|
1167
|
+
ok: true,
|
|
1168
|
+
value: definition
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
/** Read `slots.json`: a list of `{ id, name, capacity }` that adds to the usual slots or changes them. */
|
|
1172
|
+
function parseSlotsFile(text) {
|
|
1173
|
+
const issues = [];
|
|
1174
|
+
let data;
|
|
1175
|
+
try {
|
|
1176
|
+
data = JSON.parse(text.replace(/^/, ""));
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
return {
|
|
1179
|
+
ok: false,
|
|
1180
|
+
issues: [{
|
|
1181
|
+
path: "",
|
|
1182
|
+
message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
1183
|
+
}]
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
if (!Array.isArray(data)) return {
|
|
1187
|
+
ok: false,
|
|
1188
|
+
issues: [{
|
|
1189
|
+
path: "",
|
|
1190
|
+
message: "expected a list of slots"
|
|
1191
|
+
}]
|
|
1192
|
+
};
|
|
1193
|
+
const slots = [];
|
|
1194
|
+
data.forEach((entry, index) => {
|
|
1195
|
+
const at = `[${index}]`;
|
|
1196
|
+
if (typeof entry !== "object" || entry === null) {
|
|
1197
|
+
issues.push({
|
|
1198
|
+
path: at,
|
|
1199
|
+
message: "must be an object"
|
|
1200
|
+
});
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
const { id, name, capacity } = entry;
|
|
1204
|
+
if (typeof id !== "string" || !SLOT_ID.test(id)) issues.push({
|
|
1205
|
+
path: `${at}.id`,
|
|
1206
|
+
message: "must be lowercase letters, digits, \"-\" or \"_\""
|
|
1207
|
+
});
|
|
1208
|
+
if (typeof name !== "string" || name.trim() === "") issues.push({
|
|
1209
|
+
path: `${at}.name`,
|
|
1210
|
+
message: "is required"
|
|
1211
|
+
});
|
|
1212
|
+
if (typeof capacity !== "number" || !Number.isInteger(capacity) || capacity < 1) issues.push({
|
|
1213
|
+
path: `${at}.capacity`,
|
|
1214
|
+
message: "must be a whole number from 1"
|
|
1215
|
+
});
|
|
1216
|
+
if (typeof id === "string" && typeof name === "string" && typeof capacity === "number") slots.push({
|
|
1217
|
+
id,
|
|
1218
|
+
name: name.trim(),
|
|
1219
|
+
capacity
|
|
1220
|
+
});
|
|
1221
|
+
});
|
|
1222
|
+
return issues.length > 0 ? {
|
|
1223
|
+
ok: false,
|
|
1224
|
+
issues
|
|
1225
|
+
} : {
|
|
1226
|
+
ok: true,
|
|
1227
|
+
value: slots
|
|
1228
|
+
};
|
|
1229
|
+
}
|
|
1230
|
+
//#endregion
|
|
1231
|
+
//#region src/host/locations/location-file.ts
|
|
1232
|
+
const LOCATION_FILE_NAME = "location.json";
|
|
1233
|
+
const FEATURE_KEY = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]{0,59}$/u;
|
|
1234
|
+
function readFeatures(reader) {
|
|
1235
|
+
const features = reader.objects("features").flatMap((feature) => {
|
|
1236
|
+
const key = feature.string("id", { required: true });
|
|
1237
|
+
const name = feature.string("name", { required: true });
|
|
1238
|
+
if (key !== void 0 && !FEATURE_KEY.test(key)) feature.fail("id", "must be letters, digits, \"-\" or \"_\", at most 60");
|
|
1239
|
+
return key === void 0 || name === void 0 ? [] : [{
|
|
1240
|
+
key,
|
|
1241
|
+
name,
|
|
1242
|
+
description: feature.text("description")
|
|
1243
|
+
}];
|
|
1244
|
+
});
|
|
1245
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1246
|
+
features.forEach((feature, index) => {
|
|
1247
|
+
if (seen.has(feature.key)) reader.fail(`features[${index}].id`, `"${feature.key}" is used twice in this place`);
|
|
1248
|
+
seen.add(feature.key);
|
|
1249
|
+
});
|
|
1250
|
+
if (features.length > 30) reader.fail("features", `a place has at most 30 features`);
|
|
1251
|
+
return features;
|
|
1252
|
+
}
|
|
1253
|
+
function readExits(reader) {
|
|
1254
|
+
const exits = reader.objects("exits").flatMap((exit) => {
|
|
1255
|
+
const to = exit.string("to", { required: true });
|
|
1256
|
+
const travelSeconds = exit.number("travel_time_seconds", { min: 0 });
|
|
1257
|
+
if (travelSeconds !== void 0 && !Number.isInteger(travelSeconds)) exit.fail("travel_time_seconds", "must be a whole number of seconds");
|
|
1258
|
+
const back = exit.string("back_description");
|
|
1259
|
+
const oneWay = exit.raw("one_way");
|
|
1260
|
+
if (oneWay !== void 0 && typeof oneWay !== "boolean") exit.fail("one_way", "must be true or false");
|
|
1261
|
+
return to === void 0 ? [] : [{
|
|
1262
|
+
to,
|
|
1263
|
+
description: exit.text("description"),
|
|
1264
|
+
oneWay: oneWay === true,
|
|
1265
|
+
...back === void 0 ? {} : { backDescription: back },
|
|
1266
|
+
...travelSeconds === void 0 || !Number.isInteger(travelSeconds) ? {} : { travelSeconds },
|
|
1267
|
+
state: exit.oneOf("state", EXIT_STATES, "open"),
|
|
1268
|
+
note: exit.text("note"),
|
|
1269
|
+
openedBy: exit.strings("opened_by")
|
|
1270
|
+
}];
|
|
1271
|
+
});
|
|
1272
|
+
if (exits.length > 30) reader.fail("exits", `a place has at most 30 exits`);
|
|
1273
|
+
return exits;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Read a `location.json` into the canonical place definition.
|
|
1277
|
+
* @param fallbackId - used when the file sets no `id`; the name of its folder.
|
|
1278
|
+
*/
|
|
1279
|
+
function parseLocationFile(text, fallbackId) {
|
|
1280
|
+
const issues = [];
|
|
1281
|
+
const reader = Reader.fromJson(text, issues);
|
|
1282
|
+
if (reader === void 0) return {
|
|
1283
|
+
ok: false,
|
|
1284
|
+
issues
|
|
1285
|
+
};
|
|
1286
|
+
const id = readIdentifier(reader, fallbackId) ?? fallbackId;
|
|
1287
|
+
const name = reader.string("name", { required: true });
|
|
1288
|
+
const parent = reader.string("parent");
|
|
1289
|
+
const variables = readVariableValues(reader);
|
|
1290
|
+
const visualIdentity = readVisualIdentity(reader);
|
|
1291
|
+
const location = {
|
|
1292
|
+
id,
|
|
1293
|
+
name: name ?? "",
|
|
1294
|
+
description: reader.text("description"),
|
|
1295
|
+
...visualIdentity === void 0 ? {} : { visualIdentity },
|
|
1296
|
+
...parent === void 0 ? {} : { parent },
|
|
1297
|
+
features: readFeatures(reader),
|
|
1298
|
+
exits: readExits(reader),
|
|
1299
|
+
...variables === void 0 ? {} : { variables }
|
|
1300
|
+
};
|
|
1301
|
+
return issues.length > 0 ? {
|
|
1302
|
+
ok: false,
|
|
1303
|
+
issues
|
|
1304
|
+
} : {
|
|
1305
|
+
ok: true,
|
|
1306
|
+
value: location
|
|
1307
|
+
};
|
|
1308
|
+
}
|
|
1309
|
+
//#endregion
|
|
1310
|
+
//#region src/host/lore/lore-file.ts
|
|
1311
|
+
const LORE_FILE_NAME = "lore.json";
|
|
1312
|
+
function instant(reader, key) {
|
|
1313
|
+
const value = reader.string(key);
|
|
1314
|
+
if (value === void 0) return void 0;
|
|
1315
|
+
const parsed = Date.parse(value);
|
|
1316
|
+
if (!Number.isFinite(parsed)) {
|
|
1317
|
+
reader.fail(key, "must be an ISO date or date-time");
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1320
|
+
return parsed;
|
|
1321
|
+
}
|
|
1322
|
+
function parseLoreFile(text, fallbackId) {
|
|
1323
|
+
const issues = [];
|
|
1324
|
+
const reader = Reader.fromJson(text, issues);
|
|
1325
|
+
if (reader === void 0) return {
|
|
1326
|
+
ok: false,
|
|
1327
|
+
issues
|
|
1328
|
+
};
|
|
1329
|
+
const id = readIdentifier(reader, fallbackId) ?? fallbackId;
|
|
1330
|
+
const title = reader.string("title", { required: true }) ?? "";
|
|
1331
|
+
const subjects = reader.objects("subjects").flatMap((entry) => {
|
|
1332
|
+
const kind = entry.oneOf("kind", LORE_SUBJECT_KINDS, "lore");
|
|
1333
|
+
const subjectId = entry.string("id", { required: true });
|
|
1334
|
+
return subjectId === void 0 ? [] : [{
|
|
1335
|
+
kind,
|
|
1336
|
+
id: subjectId
|
|
1337
|
+
}];
|
|
1338
|
+
});
|
|
1339
|
+
const startsAt = instant(reader, "starts_at");
|
|
1340
|
+
const endsAt = instant(reader, "ends_at");
|
|
1341
|
+
if (startsAt !== void 0 && endsAt !== void 0 && endsAt < startsAt) reader.fail("ends_at", "must not be before starts_at");
|
|
1342
|
+
const scope = reader.oneOf("scope", LORE_SCOPES, "listed");
|
|
1343
|
+
const knownBy = reader.strings("known_by");
|
|
1344
|
+
if (scope === "everyone" && knownBy.length > 0) reader.fail("known_by", "applies only to lore whose scope is \"listed\"");
|
|
1345
|
+
const value = {
|
|
1346
|
+
id,
|
|
1347
|
+
title,
|
|
1348
|
+
kind: reader.oneOf("kind", LORE_KINDS, "other"),
|
|
1349
|
+
scope,
|
|
1350
|
+
knownBy,
|
|
1351
|
+
summary: reader.text("summary"),
|
|
1352
|
+
body: reader.text("body"),
|
|
1353
|
+
subjects,
|
|
1354
|
+
related: reader.strings("related"),
|
|
1355
|
+
sources: reader.strings("sources"),
|
|
1356
|
+
...startsAt === void 0 ? {} : { startsAt },
|
|
1357
|
+
...endsAt === void 0 ? {} : { endsAt }
|
|
1358
|
+
};
|
|
1359
|
+
return issues.length === 0 ? {
|
|
1360
|
+
ok: true,
|
|
1361
|
+
value
|
|
1362
|
+
} : {
|
|
1363
|
+
ok: false,
|
|
1364
|
+
issues
|
|
1365
|
+
};
|
|
1366
|
+
}
|
|
1367
|
+
//#endregion
|
|
1368
|
+
//#region src/host/variables/load.ts
|
|
1369
|
+
const VARIABLES_FILE_NAME = "variables.json";
|
|
1370
|
+
function readDefinition(reader) {
|
|
1371
|
+
const key = reader.string("key", { required: true });
|
|
1372
|
+
const name = reader.string("name", { required: true });
|
|
1373
|
+
const kind = reader.oneOf("kind", VARIABLE_KINDS, "number");
|
|
1374
|
+
const subject = reader.oneOf("subject", VARIABLE_SUBJECTS, "character");
|
|
1375
|
+
const visibility = reader.oneOf("visibility", VARIABLE_VISIBILITIES, "public");
|
|
1376
|
+
const min = reader.number("min");
|
|
1377
|
+
const max = reader.number("max");
|
|
1378
|
+
const defaultValue = reader.raw("default");
|
|
1379
|
+
if (defaultValue !== void 0 && typeof defaultValue !== "number" && typeof defaultValue !== "boolean" && typeof defaultValue !== "string") reader.fail("default", "must be a number, true or false, or text");
|
|
1380
|
+
const flag = (field) => {
|
|
1381
|
+
const value = reader.raw(field);
|
|
1382
|
+
if (value !== void 0 && typeof value !== "boolean") reader.fail(field, "must be true or false");
|
|
1383
|
+
return typeof value === "boolean" ? value : void 0;
|
|
1384
|
+
};
|
|
1385
|
+
const integer = flag("integer");
|
|
1386
|
+
const baseline = flag("baseline");
|
|
1387
|
+
const always = flag("always");
|
|
1388
|
+
const bands = reader.objects("bands").flatMap((band) => {
|
|
1389
|
+
const upTo = band.number("up_to", {});
|
|
1390
|
+
const label = band.string("label", { required: true });
|
|
1391
|
+
return upTo === void 0 || label === void 0 ? [] : [{
|
|
1392
|
+
upTo,
|
|
1393
|
+
label
|
|
1394
|
+
}];
|
|
1395
|
+
});
|
|
1396
|
+
if (key === void 0 || name === void 0) return void 0;
|
|
1397
|
+
const only = reader.strings("only");
|
|
1398
|
+
const options = reader.strings("options");
|
|
1399
|
+
return {
|
|
1400
|
+
key,
|
|
1401
|
+
name,
|
|
1402
|
+
kind,
|
|
1403
|
+
subject,
|
|
1404
|
+
visibility,
|
|
1405
|
+
...reader.raw("description") === void 0 ? {} : { description: reader.text("description") },
|
|
1406
|
+
only,
|
|
1407
|
+
options,
|
|
1408
|
+
bands,
|
|
1409
|
+
...min === void 0 ? {} : { min },
|
|
1410
|
+
...max === void 0 ? {} : { max },
|
|
1411
|
+
...integer === void 0 ? {} : { integer },
|
|
1412
|
+
...baseline === void 0 ? {} : { baseline },
|
|
1413
|
+
...always === void 0 ? {} : { always },
|
|
1414
|
+
...defaultValue === void 0 || typeof defaultValue === "number" && !Number.isFinite(defaultValue) ? {} : { default: defaultValue }
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
/** Read `variables.json`: a list of what the world tracks. */
|
|
1418
|
+
function parseVariablesFile(text) {
|
|
1419
|
+
const issues = [];
|
|
1420
|
+
let data;
|
|
1421
|
+
try {
|
|
1422
|
+
data = JSON.parse(text.replace(/^/, ""));
|
|
1423
|
+
} catch (error) {
|
|
1424
|
+
return {
|
|
1425
|
+
ok: false,
|
|
1426
|
+
issues: [{
|
|
1427
|
+
path: "",
|
|
1428
|
+
message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
1429
|
+
}]
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
if (!Array.isArray(data)) return {
|
|
1433
|
+
ok: false,
|
|
1434
|
+
issues: [{
|
|
1435
|
+
path: "",
|
|
1436
|
+
message: "expected a list of variables"
|
|
1437
|
+
}]
|
|
1438
|
+
};
|
|
1439
|
+
const reader = Reader.fromJson(JSON.stringify({ variables: data }), issues);
|
|
1440
|
+
if (reader === void 0) return {
|
|
1441
|
+
ok: false,
|
|
1442
|
+
issues
|
|
1443
|
+
};
|
|
1444
|
+
const defs = reader.objects("variables").flatMap((entry) => readDefinition(entry) ?? []);
|
|
1445
|
+
return issues.length > 0 ? {
|
|
1446
|
+
ok: false,
|
|
1447
|
+
issues: issues.map((issue) => ({
|
|
1448
|
+
...issue,
|
|
1449
|
+
path: issue.path.replace(/^variables/, "")
|
|
1450
|
+
}))
|
|
1451
|
+
} : {
|
|
1452
|
+
ok: true,
|
|
1453
|
+
value: defs
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
/** Read the world's own variables: an optional `<world>/variables.json`. A world with none tracks only what every story does. */
|
|
1457
|
+
async function loadVariables(worldDir) {
|
|
1458
|
+
const result = {
|
|
1459
|
+
defs: [],
|
|
1460
|
+
problems: []
|
|
1461
|
+
};
|
|
1462
|
+
const file = join(worldDir, VARIABLES_FILE_NAME);
|
|
1463
|
+
try {
|
|
1464
|
+
result.defs = await readDocument(file, parseVariablesFile, result.problems) ?? [];
|
|
1465
|
+
} catch (error) {
|
|
1466
|
+
if (error.code !== "ENOENT") result.problems.push({
|
|
1467
|
+
path: file,
|
|
1468
|
+
message: errorMessage(error)
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
return result;
|
|
1472
|
+
}
|
|
1473
|
+
/**
|
|
1474
|
+
* What is wrong with the variables of a world and the values it starts with, found before anything is created: a
|
|
1475
|
+
* declaration that cannot be one, a repeated key, a subject a variable is limited to that does not exist, a value for a
|
|
1476
|
+
* variable that is not declared, does not apply to what has it, or is not one it can have.
|
|
1477
|
+
*/
|
|
1478
|
+
function variableProblems(world) {
|
|
1479
|
+
const problems = [];
|
|
1480
|
+
const scratch = createSessionStore(":memory:", {
|
|
1481
|
+
id: "scratch",
|
|
1482
|
+
name: "scratch",
|
|
1483
|
+
world: {
|
|
1484
|
+
id: "scratch",
|
|
1485
|
+
name: "scratch"
|
|
1486
|
+
}
|
|
1487
|
+
}, { vectors: false });
|
|
1488
|
+
try {
|
|
1489
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1490
|
+
world.defs.forEach((def, index) => {
|
|
1491
|
+
if (seen.has(def.key)) problems.push(`variables.json[${index}]: "${def.key}" is declared twice`);
|
|
1492
|
+
seen.add(def.key);
|
|
1493
|
+
try {
|
|
1494
|
+
scratch.variables.define(def);
|
|
1495
|
+
} catch (error) {
|
|
1496
|
+
problems.push(`variables.json[${index}]: ${errorMessage(error)}`);
|
|
1497
|
+
}
|
|
1498
|
+
});
|
|
1499
|
+
const keys = {
|
|
1500
|
+
character: new Set(world.characters.map((entry) => entry.id)),
|
|
1501
|
+
item: new Set(world.items.map((entry) => entry.id)),
|
|
1502
|
+
location: new Set(world.locations.map((entry) => entry.id))
|
|
1503
|
+
};
|
|
1504
|
+
for (const def of scratch.variables.defs()) for (const key of def.only) if (def.subject !== "world" && !keys[def.subject].has(key)) problems.push(`variables.json: ${def.key}: "${key}" is not a ${def.subject} of this world`);
|
|
1505
|
+
const check = (kind, who, values) => {
|
|
1506
|
+
for (const [key, value] of Object.entries(values ?? {})) {
|
|
1507
|
+
const def = scratch.variables.def(key);
|
|
1508
|
+
if (def === void 0) {
|
|
1509
|
+
problems.push(`${who}: variables.${key}: no such variable is declared (variables.json)`);
|
|
1510
|
+
continue;
|
|
1511
|
+
}
|
|
1512
|
+
if (def.subject !== kind) {
|
|
1513
|
+
problems.push(`${who}: variables.${key}: ${def.name} is about ${def.subject === "world" ? "the world" : `a ${def.subject}`}, not ${kind === "world" ? "the world" : `a ${kind}`}`);
|
|
1514
|
+
continue;
|
|
1515
|
+
}
|
|
1516
|
+
if (kind !== "world" && def.only.length > 0 && !def.only.includes(who.split(": ")[0])) problems.push(`${who}: variables.${key}: ${def.name} does not apply to it`);
|
|
1517
|
+
const issue = valueIssue(def, value);
|
|
1518
|
+
if (issue !== void 0) problems.push(`${who}: variables.${key}: ${issue}`);
|
|
1519
|
+
}
|
|
1520
|
+
};
|
|
1521
|
+
for (const entry of world.characters) check("character", `${entry.id}: character`, entry.variables);
|
|
1522
|
+
for (const entry of world.items) check("item", `${entry.id}: item`, entry.variables);
|
|
1523
|
+
for (const entry of world.locations) check("location", `${entry.id}: place`, entry.variables);
|
|
1524
|
+
check("world", "world.json", world.values);
|
|
1525
|
+
} finally {
|
|
1526
|
+
scratch.close();
|
|
1527
|
+
}
|
|
1528
|
+
return problems;
|
|
1529
|
+
}
|
|
1530
|
+
//#endregion
|
|
1531
|
+
//#region src/shared/import-card.ts
|
|
1532
|
+
/** The message the plugin sends on the player's behalf to start the import in the new world's authoring chat. */
|
|
1533
|
+
const IMPORT_COMMAND = "/import-st";
|
|
1534
|
+
/** The command in a message, with the card it names, or nothing when the message is not the command. */
|
|
1535
|
+
function parseImportCommand(text) {
|
|
1536
|
+
const value = text.trimStart();
|
|
1537
|
+
if (value.slice(0, 10).toLowerCase() !== "/import-st" || value.length > 10 && !/\s/u.test(value[10])) return void 0;
|
|
1538
|
+
const body = value.slice(10).trimStart();
|
|
1539
|
+
const boundary = body.search(/\s/u);
|
|
1540
|
+
return boundary < 0 ? {
|
|
1541
|
+
card: body,
|
|
1542
|
+
request: ""
|
|
1543
|
+
} : {
|
|
1544
|
+
card: body.slice(0, boundary),
|
|
1545
|
+
request: body.slice(boundary).trim()
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
//#endregion
|
|
1549
|
+
//#region src/host/import/store.ts
|
|
1550
|
+
const IMPORT_FOLDER = ".import";
|
|
1551
|
+
const CARD_FILE = "card.json";
|
|
1552
|
+
const CHOICES_FILE = "choices.json";
|
|
1553
|
+
const PICTURE_FILE = "picture.png";
|
|
1554
|
+
const IMPORT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
1555
|
+
/** An upload that nobody started an import from is forgotten after this long. */
|
|
1556
|
+
const ABANDONED_AFTER_MS = 864e5;
|
|
1557
|
+
var ImportNotFoundError = class extends Error {};
|
|
1558
|
+
/** What the person importing is offered to begin with: the card's own name, the entries it left switched on, and its first message (an alternate greeting when it has none). */
|
|
1559
|
+
function defaultChoices(card) {
|
|
1560
|
+
const opening = card.firstMessage.trim() !== "" ? { kind: "first" } : card.alternateGreetings.some((greeting) => greeting.trim() !== "") ? {
|
|
1561
|
+
kind: "alternate",
|
|
1562
|
+
index: card.alternateGreetings.findIndex((greeting) => greeting.trim() !== "")
|
|
1563
|
+
} : { kind: "none" };
|
|
1564
|
+
return {
|
|
1565
|
+
name: card.name.slice(0, 200),
|
|
1566
|
+
disabledEntries: (card.book?.entries ?? []).filter((entry) => !entry.enabled).map((entry) => entry.id),
|
|
1567
|
+
opening
|
|
1568
|
+
};
|
|
1569
|
+
}
|
|
1570
|
+
/** The text of the opening a choice names; nothing when the choice is none or names nothing. */
|
|
1571
|
+
function openingText(card, opening) {
|
|
1572
|
+
const found = opening.kind === "first" ? card.firstMessage : opening.kind === "alternate" ? card.alternateGreetings[opening.index] : void 0;
|
|
1573
|
+
return found === void 0 || found.trim() === "" ? void 0 : found;
|
|
1574
|
+
}
|
|
1575
|
+
/** Why a set of choices cannot be used for a card; none when it can. */
|
|
1576
|
+
function choiceProblems(card, choices) {
|
|
1577
|
+
const problems = [];
|
|
1578
|
+
if (choices.name.trim() === "") problems.push("the world needs a name");
|
|
1579
|
+
if (choices.name.length > 200) problems.push(`the name is longer than 200 characters`);
|
|
1580
|
+
const known = new Set((card.book?.entries ?? []).map((entry) => entry.id));
|
|
1581
|
+
for (const id of choices.disabledEntries) if (!known.has(id)) problems.push(`there is no entry "${id}"`);
|
|
1582
|
+
if (choices.opening.kind !== "none" && openingText(card, choices.opening) === void 0) problems.push("the opening chosen is empty or does not exist");
|
|
1583
|
+
return problems;
|
|
1584
|
+
}
|
|
1585
|
+
/** Reads the choices of a body that came from the browser: every field is checked. */
|
|
1586
|
+
function parseChoices(value) {
|
|
1587
|
+
const problems = [];
|
|
1588
|
+
const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
1589
|
+
if (input === void 0) throw new InvalidEditProblems(["the choices must be an object"]);
|
|
1590
|
+
const name = typeof input["name"] === "string" ? input["name"].trim() : (problems.push("name must be text"), "");
|
|
1591
|
+
const disabled = Array.isArray(input["disabledEntries"]) && input["disabledEntries"].every((entry) => typeof entry === "string") ? input["disabledEntries"] : (problems.push("disabledEntries must be a list of ids"), []);
|
|
1592
|
+
const raw = typeof input["opening"] === "object" && input["opening"] !== null ? input["opening"] : void 0;
|
|
1593
|
+
let opening = { kind: "none" };
|
|
1594
|
+
if (raw?.["kind"] === "first") opening = { kind: "first" };
|
|
1595
|
+
else if (raw?.["kind"] === "alternate" && Number.isInteger(raw["index"]) && raw["index"] >= 0) opening = {
|
|
1596
|
+
kind: "alternate",
|
|
1597
|
+
index: raw["index"]
|
|
1598
|
+
};
|
|
1599
|
+
else if (raw?.["kind"] !== "none") problems.push("opening must be first, alternate with an index, or none");
|
|
1600
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
1601
|
+
return {
|
|
1602
|
+
name,
|
|
1603
|
+
disabledEntries: [...new Set(disabled)],
|
|
1604
|
+
opening
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
async function readJson(file) {
|
|
1608
|
+
return JSON.parse(await readFile(file, "utf8"));
|
|
1609
|
+
}
|
|
1610
|
+
/** What an import folder holds: the card as it was read, what the person chose, and the card's picture when it had one. */
|
|
1611
|
+
async function readImportFolder(directory) {
|
|
1612
|
+
const [card, choices, picture] = await Promise.all([
|
|
1613
|
+
readJson(join(directory, CARD_FILE)),
|
|
1614
|
+
readJson(join(directory, CHOICES_FILE)),
|
|
1615
|
+
stat(join(directory, PICTURE_FILE)).then(() => true, () => false)
|
|
1616
|
+
]);
|
|
1617
|
+
return {
|
|
1618
|
+
card,
|
|
1619
|
+
choices,
|
|
1620
|
+
hasPicture: picture
|
|
1621
|
+
};
|
|
1622
|
+
}
|
|
1623
|
+
async function writeChoices(directory, choices) {
|
|
1624
|
+
const file = join(directory, CHOICES_FILE);
|
|
1625
|
+
await writeFile(`${file}.writing`, JSON.stringify(choices, null, 2));
|
|
1626
|
+
await rename(`${file}.writing`, file);
|
|
1627
|
+
}
|
|
1628
|
+
/** Uploaded cards waiting to become worlds: one folder each under `<root>/imports/`. */
|
|
1629
|
+
var ImportStore = class {
|
|
1630
|
+
root;
|
|
1631
|
+
constructor(root) {
|
|
1632
|
+
this.root = root;
|
|
1633
|
+
}
|
|
1634
|
+
folder(id) {
|
|
1635
|
+
if (!IMPORT_ID.test(id)) throw new ImportNotFoundError(`there is no import "${id}"`);
|
|
1636
|
+
return join(this.root(), "imports", id);
|
|
1637
|
+
}
|
|
1638
|
+
async create(card, picture) {
|
|
1639
|
+
await this.forgetAbandoned();
|
|
1640
|
+
const id = randomUUID();
|
|
1641
|
+
const directory = this.folder(id);
|
|
1642
|
+
await mkdir(directory, { recursive: true });
|
|
1643
|
+
try {
|
|
1644
|
+
await writeFile(join(directory, CARD_FILE), JSON.stringify(card));
|
|
1645
|
+
if (picture !== void 0) await writeFile(join(directory, PICTURE_FILE), picture);
|
|
1646
|
+
await writeChoices(directory, defaultChoices(card));
|
|
1647
|
+
} catch (error) {
|
|
1648
|
+
await rm(directory, {
|
|
1649
|
+
recursive: true,
|
|
1650
|
+
force: true
|
|
1651
|
+
});
|
|
1652
|
+
throw error;
|
|
1653
|
+
}
|
|
1654
|
+
return await this.read(id);
|
|
1655
|
+
}
|
|
1656
|
+
async read(id) {
|
|
1657
|
+
const directory = this.folder(id);
|
|
1658
|
+
try {
|
|
1659
|
+
const { card, choices, hasPicture } = await readImportFolder(directory);
|
|
1660
|
+
return {
|
|
1661
|
+
id,
|
|
1662
|
+
card,
|
|
1663
|
+
choices,
|
|
1664
|
+
hasAvatar: hasPicture
|
|
1665
|
+
};
|
|
1666
|
+
} catch (error) {
|
|
1667
|
+
if (error.code === "ENOENT") throw new ImportNotFoundError(`there is no import "${id}"`);
|
|
1668
|
+
throw error;
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
/** The picture of an upload, when it has one. @throws {ImportNotFoundError} when there is no such import or it has no picture. */
|
|
1672
|
+
async picture(id) {
|
|
1673
|
+
const file = join(this.folder(id), PICTURE_FILE);
|
|
1674
|
+
try {
|
|
1675
|
+
return {
|
|
1676
|
+
file,
|
|
1677
|
+
size: (await stat(file)).size
|
|
1678
|
+
};
|
|
1679
|
+
} catch (error) {
|
|
1680
|
+
if (error.code === "ENOENT") throw new ImportNotFoundError(`the import "${id}" has no picture`);
|
|
1681
|
+
throw error;
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
/** @throws {InvalidEditProblems} when the choices cannot be used for the card. */
|
|
1685
|
+
async choose(id, choices) {
|
|
1686
|
+
const { card } = await this.read(id);
|
|
1687
|
+
const problems = choiceProblems(card, choices);
|
|
1688
|
+
if (problems.length > 0) throw new InvalidEditProblems(problems);
|
|
1689
|
+
await writeChoices(this.folder(id), choices);
|
|
1690
|
+
return await this.read(id);
|
|
1691
|
+
}
|
|
1692
|
+
async discard(id) {
|
|
1693
|
+
await this.read(id);
|
|
1694
|
+
await rm(this.folder(id), {
|
|
1695
|
+
recursive: true,
|
|
1696
|
+
force: true
|
|
1697
|
+
});
|
|
1698
|
+
}
|
|
1699
|
+
/** Moves the folder into the world it became, as `.import/`, or into the given place of the world (a card that updates it waits there). */
|
|
1700
|
+
async adopt(id, worldDirectory, into = IMPORT_FOLDER) {
|
|
1701
|
+
const from = this.folder(id);
|
|
1702
|
+
const to = join(worldDirectory, into);
|
|
1703
|
+
await mkdir(join(to, ".."), { recursive: true });
|
|
1704
|
+
try {
|
|
1705
|
+
await rename(from, to);
|
|
1706
|
+
} catch (error) {
|
|
1707
|
+
if (error.code !== "EXDEV") throw error;
|
|
1708
|
+
await cp(from, to, { recursive: true });
|
|
1709
|
+
await rm(from, {
|
|
1710
|
+
recursive: true,
|
|
1711
|
+
force: true
|
|
1712
|
+
});
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
async forgetAbandoned() {
|
|
1716
|
+
const parent = join(this.root(), "imports");
|
|
1717
|
+
let names;
|
|
1718
|
+
try {
|
|
1719
|
+
names = await readdir(parent);
|
|
1720
|
+
} catch (error) {
|
|
1721
|
+
if (error.code === "ENOENT") return;
|
|
1722
|
+
throw error;
|
|
1723
|
+
}
|
|
1724
|
+
const limit = Date.now() - ABANDONED_AFTER_MS;
|
|
1725
|
+
for (const name of names) {
|
|
1726
|
+
if (!IMPORT_ID.test(name)) continue;
|
|
1727
|
+
const { mtimeMs } = await stat(join(parent, name));
|
|
1728
|
+
if (mtimeMs < limit) await rm(join(parent, name), {
|
|
1729
|
+
recursive: true,
|
|
1730
|
+
force: true
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
};
|
|
1735
|
+
//#endregion
|
|
1736
|
+
//#region src/host/import/items.ts
|
|
1737
|
+
/** The longest a piece goes into one call. Longer entries are cut into parts at the end of a paragraph. */
|
|
1738
|
+
const MAX_ITEM_CHARS = 5e3;
|
|
1739
|
+
/** What stands for the player in the text a model reads. The card's own `{{user}}` cannot: the system prompt of an agent reads double braces as a variable of its own. */
|
|
1740
|
+
const PLAYER_MARKER = "[PLAYER]";
|
|
1741
|
+
/** Macros and markup of the tool that wrote the card, taken out of text a model reads: the card's own name stands for `{{char}}`; the player becomes the marker `[PLAYER]`. */
|
|
1742
|
+
function cleanText(text, cardName) {
|
|
1743
|
+
return text.replace(/\r\n?/g, "\n").replace(/<!--[\s\S]*?-->/g, "").replace(/<%[=_\-#]?[\s\S]*?[_\-]?%>/g, "").replace(/\{\{\s*\/\/[\s\S]*?\}\}/g, "").replace(/\{\{\s*char\s*\}\}|<char>|<bot>/gi, cardName).replace(/\{\{\s*user\s*\}\}|<user>/gi, PLAYER_MARKER).split("\n").filter((line) => line.trim().toUpperCase() !== "<START>").join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
1744
|
+
}
|
|
1745
|
+
/** Cuts a text into parts of at most `max` characters, at the end of a paragraph, or of a line, or anywhere when there is no choice. */
|
|
1746
|
+
function partsOf(text, max = MAX_ITEM_CHARS) {
|
|
1747
|
+
const parts = [];
|
|
1748
|
+
let rest = text;
|
|
1749
|
+
while (rest.length > max) {
|
|
1750
|
+
const window = rest.slice(0, max);
|
|
1751
|
+
const cut = Math.max(window.lastIndexOf("\n\n"), window.lastIndexOf("\n"), window.lastIndexOf("。"), window.lastIndexOf(". "));
|
|
1752
|
+
const at = cut > max / 2 ? cut + 1 : max;
|
|
1753
|
+
parts.push(rest.slice(0, at).trim());
|
|
1754
|
+
rest = rest.slice(at).trim();
|
|
1755
|
+
}
|
|
1756
|
+
if (rest !== "") parts.push(rest);
|
|
1757
|
+
return parts;
|
|
1758
|
+
}
|
|
1759
|
+
function itemsOf(id, label, title, keys, raw, cardName, constant = false) {
|
|
1760
|
+
const text = cleanText(raw, cardName);
|
|
1761
|
+
if (text === "") return [];
|
|
1762
|
+
const parts = partsOf(text);
|
|
1763
|
+
return parts.map((part, index) => ({
|
|
1764
|
+
id: parts.length === 1 ? id : `${id}#${index + 1}`,
|
|
1765
|
+
label: parts.length === 1 ? label : `${label} (part ${index + 1})`,
|
|
1766
|
+
title,
|
|
1767
|
+
keys,
|
|
1768
|
+
text: part,
|
|
1769
|
+
...constant ? { constant: true } : {}
|
|
1770
|
+
}));
|
|
1771
|
+
}
|
|
1772
|
+
/**
|
|
1773
|
+
* The pieces of a card that are read for what the world is made of: what describes the characters and the setting, the opening the person chose, and the lorebook
|
|
1774
|
+
* entries they left on. The instructions to the narrator (system prompt, post-history instructions) and the creator's notes are not among them: they are not part of the world.
|
|
1775
|
+
*/
|
|
1776
|
+
function itemise(card, choices) {
|
|
1777
|
+
const name = card.name;
|
|
1778
|
+
const opening = openingText(card, choices.opening);
|
|
1779
|
+
const off = new Set(choices.disabledEntries);
|
|
1780
|
+
return [
|
|
1781
|
+
...itemsOf("field:description", "description", "", [], card.description, name),
|
|
1782
|
+
...itemsOf("field:personality", "personality", "", [], card.personality, name),
|
|
1783
|
+
...itemsOf("field:scenario", "scenario", "", [], card.scenario, name),
|
|
1784
|
+
...itemsOf("field:example", "example messages", "", [], card.messageExample, name),
|
|
1785
|
+
...opening === void 0 ? [] : itemsOf("field:opening", "opening", "", [], opening, name),
|
|
1786
|
+
...(card.book?.entries ?? []).filter((entry) => !off.has(entry.id)).flatMap((entry) => itemsOf(entry.id, entry.title === "" ? entry.id : `entry “${entry.title}”`, entry.title, entry.keys, entry.content, name, entry.constant))
|
|
1787
|
+
];
|
|
1788
|
+
}
|
|
1789
|
+
/** The word a text uses for the player: the player's character when it is named, otherwise a plain word in the text's own script. */
|
|
1790
|
+
function playerWord(text, name) {
|
|
1791
|
+
if (name !== void 0) return name;
|
|
1792
|
+
return /[㐀-鿿]/.test(text) ? "玩家" : "the player";
|
|
1793
|
+
}
|
|
1794
|
+
/** The text with the player marker replaced. */
|
|
1795
|
+
function withPlayer(text, name) {
|
|
1796
|
+
return text.replace(/\[PLAYER\]|\{\{\s*user\s*\}\}/g, playerWord(text, name));
|
|
1797
|
+
}
|
|
1798
|
+
//#endregion
|
|
1799
|
+
//#region src/host/prompts/world-prompts.ts
|
|
1800
|
+
/** The prompts that decide how the story is written and who the models are (prose and persona); every other prompt holds rules of the game. */
|
|
1801
|
+
const PROSE_PROMPTS = [
|
|
1802
|
+
"roleplay/persona",
|
|
1803
|
+
"roleplay/style",
|
|
1804
|
+
"roleplay/character-style"
|
|
1805
|
+
];
|
|
1806
|
+
function shippedFile(shipped, language, id) {
|
|
1807
|
+
return [language, "en"].map((name) => join(shipped, name, `${id}.md`)).find((path) => existsSync(path));
|
|
1808
|
+
}
|
|
1809
|
+
function fileOf(directory, language, id, shipped) {
|
|
1810
|
+
const problem = promptProblem(language, id, "x", shipped);
|
|
1811
|
+
if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story; the ones that can be carried are listed by list_world_prompts`);
|
|
1812
|
+
if (problem !== void 0 && problem.startsWith("there is no prompt")) throw new Error(problem);
|
|
1813
|
+
return join(directory, PROMPTS_FOLDER, language, `${id}.md`);
|
|
1814
|
+
}
|
|
1815
|
+
/** Every prompt of the story, in a language, and whether the world carries its own version. */
|
|
1816
|
+
function listWorldPrompts(directory, language, shipped = shippedPromptsDirectory()) {
|
|
1817
|
+
const tag = languageOf(language);
|
|
1818
|
+
return readdirSync(join(shipped, "en"), { withFileTypes: true }).filter((entry) => entry.isDirectory() && entry.name === "roleplay").flatMap((entry) => listFiles(join(shipped, "en", entry.name), `${entry.name}/`)).sort().map((id) => ({
|
|
1819
|
+
id,
|
|
1820
|
+
kind: PROSE_PROMPTS.includes(id) ? "prose" : "rules",
|
|
1821
|
+
carried: existsSync(join(directory, PROMPTS_FOLDER, tag, `${id}.md`))
|
|
1822
|
+
}));
|
|
1823
|
+
}
|
|
1824
|
+
/** A prompt as sessions of the world get it: the world's own version, else the shipped text. */
|
|
1825
|
+
function readWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
|
|
1826
|
+
const tag = languageOf(language);
|
|
1827
|
+
const own = fileOf(directory, tag, id, shipped);
|
|
1828
|
+
if (existsSync(own)) return {
|
|
1829
|
+
id,
|
|
1830
|
+
language: tag,
|
|
1831
|
+
carried: true,
|
|
1832
|
+
text: readFileSync(own, "utf8")
|
|
1833
|
+
};
|
|
1834
|
+
const original = shippedFile(shipped, tag, id);
|
|
1835
|
+
return {
|
|
1836
|
+
id,
|
|
1837
|
+
language: tag,
|
|
1838
|
+
carried: false,
|
|
1839
|
+
text: original === void 0 ? "" : readFileSync(original, "utf8")
|
|
1840
|
+
};
|
|
1841
|
+
}
|
|
1842
|
+
/** @throws {Error} when the text is not acceptable for the prompt: see `promptProblem`. */
|
|
1843
|
+
async function writeWorldPrompt(directory, language, id, text, shipped = shippedPromptsDirectory()) {
|
|
1844
|
+
const tag = languageOf(language);
|
|
1845
|
+
const file = fileOf(directory, tag, id, shipped);
|
|
1846
|
+
const problem = promptProblem(tag, id, text, shipped);
|
|
1847
|
+
if (problem !== void 0) throw new Error(problem);
|
|
1848
|
+
await mkdir(dirname(file), { recursive: true });
|
|
1849
|
+
const temporary = `${file}.tmp`;
|
|
1850
|
+
await writeFile(temporary, text.endsWith("\n") ? text : `${text}\n`);
|
|
1851
|
+
await rename(temporary, file);
|
|
1852
|
+
}
|
|
1853
|
+
/** Moves the world's own version into its `.trash`, so sessions use the shipped one again. @returns where it went. */
|
|
1854
|
+
async function deleteWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
|
|
1855
|
+
const tag = languageOf(language);
|
|
1856
|
+
const file = fileOf(directory, tag, id, shipped);
|
|
1857
|
+
if (!existsSync(file)) throw new Error(`the world carries no prompt "${id}" in ${tag}`);
|
|
1858
|
+
const aside = join(directory, ".trash", PROMPTS_FOLDER, tag, `${id}.${Date.now()}.md`);
|
|
1859
|
+
await mkdir(dirname(aside), { recursive: true });
|
|
1860
|
+
await rename(file, aside);
|
|
1861
|
+
await rm(dirname(file), { recursive: false }).catch(() => void 0);
|
|
1862
|
+
return aside;
|
|
1863
|
+
}
|
|
1864
|
+
//#endregion
|
|
1865
|
+
//#region src/host/decisions/route.ts
|
|
1866
|
+
/** The probability from which a yes is taken as a yes, for the confidence a chat asks. */
|
|
1867
|
+
const yesAt = (confidence) => (1 + confidence) / 2;
|
|
1868
|
+
/** The probability up to which a no is taken as a no. */
|
|
1869
|
+
const noAt = (confidence) => (1 - confidence) / 2;
|
|
1870
|
+
const clip = (text) => text.length > 120 ? `${text.slice(0, 119)}…` : text;
|
|
1871
|
+
const reportOf = (mode, items) => ({
|
|
1872
|
+
mode,
|
|
1873
|
+
items,
|
|
1874
|
+
decided: 0,
|
|
1875
|
+
escalated: 0,
|
|
1876
|
+
fallbacks: 0,
|
|
1877
|
+
agreed: 0,
|
|
1878
|
+
disagreed: 0,
|
|
1879
|
+
decisionMs: 0,
|
|
1880
|
+
llmMs: 0,
|
|
1881
|
+
samples: []
|
|
1882
|
+
});
|
|
1883
|
+
async function timed(run) {
|
|
1884
|
+
const started = performance.now();
|
|
1885
|
+
return {
|
|
1886
|
+
value: await run(),
|
|
1887
|
+
ms: Math.round(performance.now() - started)
|
|
1888
|
+
};
|
|
1889
|
+
}
|
|
1890
|
+
/**
|
|
1891
|
+
* Gives each key a verdict the way its site is set to: from the language model, from the decision model, from the decision model where it
|
|
1892
|
+
* is confident and the language model elsewhere, or from the language model while comparing it with the decision model. A decision model
|
|
1893
|
+
* that cannot be used never stops a story: its keys go to the language model and the report says why.
|
|
1894
|
+
*/
|
|
1895
|
+
async function routeVerdicts(route, signal) {
|
|
1896
|
+
const { mode, keys } = route;
|
|
1897
|
+
const report = reportOf(mode, keys.length);
|
|
1898
|
+
const verdicts = /* @__PURE__ */ new Map();
|
|
1899
|
+
if (keys.length === 0) return {
|
|
1900
|
+
verdicts,
|
|
1901
|
+
report
|
|
1902
|
+
};
|
|
1903
|
+
const viaLlm = async (subset) => {
|
|
1904
|
+
const { value, ms } = await timed(() => route.llm(subset));
|
|
1905
|
+
report.llmMs += ms;
|
|
1906
|
+
for (const [key, verdict] of value) verdicts.set(key, verdict);
|
|
1907
|
+
};
|
|
1908
|
+
const viaDecision = async () => {
|
|
1909
|
+
try {
|
|
1910
|
+
const { value, ms } = await timed(() => route.probabilities(keys));
|
|
1911
|
+
report.decisionMs += ms;
|
|
1912
|
+
return value;
|
|
1913
|
+
} catch (error) {
|
|
1914
|
+
if (signal.aborted) throw error;
|
|
1915
|
+
report.problem = error instanceof Error ? error.message : String(error);
|
|
1916
|
+
return;
|
|
1917
|
+
}
|
|
1918
|
+
};
|
|
1919
|
+
if (mode === "llm") {
|
|
1920
|
+
await viaLlm(keys);
|
|
1921
|
+
return {
|
|
1922
|
+
verdicts,
|
|
1923
|
+
report
|
|
1924
|
+
};
|
|
1925
|
+
}
|
|
1926
|
+
if (mode === "shadow") {
|
|
1927
|
+
const [decided] = await Promise.all([viaDecision(), viaLlm(keys)]);
|
|
1928
|
+
if (decided === void 0) return {
|
|
1929
|
+
verdicts,
|
|
1930
|
+
report
|
|
1931
|
+
};
|
|
1932
|
+
for (const key of keys) {
|
|
1933
|
+
const probability = decided.get(key);
|
|
1934
|
+
const llm = verdicts.get(key);
|
|
1935
|
+
if (probability === void 0 || llm === void 0) continue;
|
|
1936
|
+
const decision = probability >= route.yesAt;
|
|
1937
|
+
if (decision === llm) report.agreed += 1;
|
|
1938
|
+
else {
|
|
1939
|
+
report.disagreed += 1;
|
|
1940
|
+
if (report.samples.length < 20) report.samples.push({
|
|
1941
|
+
turn: route.turn,
|
|
1942
|
+
what: clip(route.what(key)),
|
|
1943
|
+
probability: Math.round(probability * 1e3) / 1e3,
|
|
1944
|
+
decision,
|
|
1945
|
+
llm
|
|
1946
|
+
});
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
return {
|
|
1950
|
+
verdicts,
|
|
1951
|
+
report
|
|
1952
|
+
};
|
|
1953
|
+
}
|
|
1954
|
+
const decided = await viaDecision();
|
|
1955
|
+
if (decided === void 0) {
|
|
1956
|
+
report.fallbacks = keys.length;
|
|
1957
|
+
await viaLlm(keys);
|
|
1958
|
+
return {
|
|
1959
|
+
verdicts,
|
|
1960
|
+
report
|
|
1961
|
+
};
|
|
1962
|
+
}
|
|
1963
|
+
const unsure = [];
|
|
1964
|
+
for (const key of keys) {
|
|
1965
|
+
const probability = decided.get(key);
|
|
1966
|
+
if (probability === void 0) {
|
|
1967
|
+
unsure.push(key);
|
|
1968
|
+
continue;
|
|
1969
|
+
}
|
|
1970
|
+
if (mode === "hybrid" && probability > route.noAt && probability < route.yesAt) unsure.push(key);
|
|
1971
|
+
else verdicts.set(key, probability >= route.yesAt);
|
|
1972
|
+
}
|
|
1973
|
+
report.decided = keys.length - unsure.length;
|
|
1974
|
+
report.escalated = unsure.length;
|
|
1975
|
+
if (unsure.length > 0) await viaLlm(unsure);
|
|
1976
|
+
return {
|
|
1977
|
+
verdicts,
|
|
1978
|
+
report
|
|
1979
|
+
};
|
|
1980
|
+
}
|
|
1981
|
+
/** Asks the decision model one yes-or-no question for each key about one state, in a single request; the answers are probabilities of yes. */
|
|
1982
|
+
async function askYesNo(service, state, asks, signal) {
|
|
1983
|
+
const questions = Object.fromEntries(asks.map(({ key, instructions }) => [key, {
|
|
1984
|
+
type: "noul",
|
|
1985
|
+
instructions
|
|
1986
|
+
}]));
|
|
1987
|
+
const { answers } = await service.decide(state, questions, {
|
|
1988
|
+
priority: "background",
|
|
1989
|
+
signal
|
|
1990
|
+
});
|
|
1991
|
+
return new Map(asks.map(({ key }) => [key, answers[key].probability]));
|
|
1992
|
+
}
|
|
1993
|
+
/**
|
|
1994
|
+
* Says once, through `say`, why a site's decision model could not be used, and again only when the reason changes, so that a story
|
|
1995
|
+
* played on without the service does not fill the log.
|
|
1996
|
+
*/
|
|
1997
|
+
function announceProblem(seen, key, report, say) {
|
|
1998
|
+
if (report.problem === void 0) {
|
|
1999
|
+
seen.delete(key);
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
if (seen.get(key) === report.problem) return;
|
|
2003
|
+
seen.set(key, report.problem);
|
|
2004
|
+
say?.(`the decision model could not be used for ${key}, the language model judged instead: ${report.problem}`);
|
|
2005
|
+
}
|
|
2006
|
+
/** The reports of several routed runs of one site as one: counts and times added, the disagreements kept up to the limit, the latest problem. */
|
|
2007
|
+
function mergeReports(mode, reports) {
|
|
2008
|
+
const merged = reportOf(mode, 0);
|
|
2009
|
+
for (const report of reports) {
|
|
2010
|
+
merged.items += report.items;
|
|
2011
|
+
merged.decided += report.decided;
|
|
2012
|
+
merged.escalated += report.escalated;
|
|
2013
|
+
merged.fallbacks += report.fallbacks;
|
|
2014
|
+
merged.agreed += report.agreed;
|
|
2015
|
+
merged.disagreed += report.disagreed;
|
|
2016
|
+
merged.decisionMs += report.decisionMs;
|
|
2017
|
+
merged.llmMs += report.llmMs;
|
|
2018
|
+
merged.samples.push(...report.samples);
|
|
2019
|
+
if (report.problem !== void 0) merged.problem = report.problem;
|
|
2020
|
+
}
|
|
2021
|
+
merged.samples = merged.samples.slice(-20);
|
|
2022
|
+
return merged;
|
|
2023
|
+
}
|
|
2024
|
+
//#endregion
|
|
2025
|
+
//#region src/host/import/roles.ts
|
|
2026
|
+
const ROLES = [
|
|
2027
|
+
"character",
|
|
2028
|
+
"player",
|
|
2029
|
+
"speech",
|
|
2030
|
+
"place",
|
|
2031
|
+
"faction",
|
|
2032
|
+
"thing",
|
|
2033
|
+
"world",
|
|
2034
|
+
"scenario",
|
|
2035
|
+
"instruction",
|
|
2036
|
+
"generator",
|
|
2037
|
+
"template",
|
|
2038
|
+
"irrelevant"
|
|
2039
|
+
];
|
|
2040
|
+
/** One place that says what every role means to the import; the stages ask the predicates below instead of listing roles. */
|
|
2041
|
+
const ROLE_TABLE = {
|
|
2042
|
+
character: {
|
|
2043
|
+
entity: "character",
|
|
2044
|
+
leftOut: false,
|
|
2045
|
+
guidance: true
|
|
2046
|
+
},
|
|
2047
|
+
player: {
|
|
2048
|
+
entity: "character",
|
|
2049
|
+
leftOut: false,
|
|
2050
|
+
guidance: true
|
|
2051
|
+
},
|
|
2052
|
+
speech: {
|
|
2053
|
+
entity: "character",
|
|
2054
|
+
leftOut: false,
|
|
2055
|
+
guidance: false
|
|
2056
|
+
},
|
|
2057
|
+
place: {
|
|
2058
|
+
entity: "place",
|
|
2059
|
+
leftOut: false,
|
|
2060
|
+
guidance: true
|
|
2061
|
+
},
|
|
2062
|
+
faction: {
|
|
2063
|
+
entity: "faction",
|
|
2064
|
+
leftOut: false,
|
|
2065
|
+
guidance: true
|
|
2066
|
+
},
|
|
2067
|
+
thing: {
|
|
2068
|
+
entity: "thing",
|
|
2069
|
+
leftOut: false,
|
|
2070
|
+
guidance: true
|
|
2071
|
+
},
|
|
2072
|
+
world: {
|
|
2073
|
+
leftOut: false,
|
|
2074
|
+
guidance: true
|
|
2075
|
+
},
|
|
2076
|
+
scenario: {
|
|
2077
|
+
leftOut: false,
|
|
2078
|
+
guidance: true
|
|
2079
|
+
},
|
|
2080
|
+
instruction: {
|
|
2081
|
+
leftOut: true,
|
|
2082
|
+
guidance: true
|
|
2083
|
+
},
|
|
2084
|
+
generator: {
|
|
2085
|
+
leftOut: false,
|
|
2086
|
+
guidance: true
|
|
2087
|
+
},
|
|
2088
|
+
template: {
|
|
2089
|
+
leftOut: true,
|
|
2090
|
+
guidance: false
|
|
2091
|
+
},
|
|
2092
|
+
irrelevant: {
|
|
2093
|
+
leftOut: true,
|
|
2094
|
+
guidance: false
|
|
2095
|
+
}
|
|
2096
|
+
};
|
|
2097
|
+
/** The role a piece is mostly about: the first the classifier named. */
|
|
2098
|
+
const mainRole = (piece) => piece.roles[0];
|
|
2099
|
+
const playsRole = (piece, role) => piece.roles.includes(role);
|
|
2100
|
+
const isLeftOut = (piece) => piece.roles.every((role) => ROLE_TABLE[role].leftOut);
|
|
2101
|
+
/** A piece that is only guidance on making people, places or things up while the story is played: the names in it are kinds and examples, not entities of the world. */
|
|
2102
|
+
const isGeneratorOnly = (piece) => playsRole(piece, "generator") && piece.roles.every((role) => role === "generator" || ROLE_TABLE[role].leftOut);
|
|
2103
|
+
/** A piece that states facts of the world, for the lore: not a rule for the narrator, not guidance on making things up. */
|
|
2104
|
+
const statesWorldFacts = (piece) => playsRole(piece, "world") && !playsRole(piece, "instruction") && !playsRole(piece, "generator");
|
|
2105
|
+
/** A piece that may hold guidance on making things up or a standing rule (the generator pieces are read whole by their own step). */
|
|
2106
|
+
const mayHoldGuidance = (piece) => !playsRole(piece, "generator") && piece.roles.some((role) => ROLE_TABLE[role].guidance);
|
|
2107
|
+
//#endregion
|
|
2108
|
+
//#region src/host/import/survey.ts
|
|
2109
|
+
const MAX_TARGETS = 10;
|
|
2110
|
+
const MAX_NAME = 100;
|
|
2111
|
+
/** What a name is when it only stands for the person using the card: not a character of the card. */
|
|
2112
|
+
const PLAYER_WORDS = /^(the |a )?(player|user|you|reader|玩家|用户|你)$/i;
|
|
2113
|
+
const isPlayerWord = (name) => PLAYER_WORDS.test(name.trim());
|
|
2114
|
+
const SHOWN_CHARS = 5e3;
|
|
2115
|
+
const CLASSIFY_SCHEMA = {
|
|
2116
|
+
type: "object",
|
|
2117
|
+
properties: {
|
|
2118
|
+
roles: {
|
|
2119
|
+
type: "array",
|
|
2120
|
+
items: {
|
|
2121
|
+
type: "string",
|
|
2122
|
+
enum: [...ROLES]
|
|
2123
|
+
},
|
|
2124
|
+
description: "What the piece is, the most important first (one to three)."
|
|
2125
|
+
},
|
|
2126
|
+
targets: {
|
|
2127
|
+
type: "array",
|
|
2128
|
+
items: {
|
|
2129
|
+
type: "object",
|
|
2130
|
+
properties: {
|
|
2131
|
+
name: { type: "string" },
|
|
2132
|
+
kind: {
|
|
2133
|
+
type: "string",
|
|
2134
|
+
enum: [
|
|
2135
|
+
"character",
|
|
2136
|
+
"place",
|
|
2137
|
+
"faction",
|
|
2138
|
+
"thing",
|
|
2139
|
+
"other"
|
|
2140
|
+
]
|
|
2141
|
+
}
|
|
2142
|
+
},
|
|
2143
|
+
required: ["name", "kind"],
|
|
2144
|
+
additionalProperties: false
|
|
2145
|
+
},
|
|
2146
|
+
description: `What it is mostly about, as the text spells the names (at most ${MAX_TARGETS}).`
|
|
2147
|
+
}
|
|
2148
|
+
},
|
|
2149
|
+
required: ["roles", "targets"],
|
|
2150
|
+
additionalProperties: false
|
|
2151
|
+
};
|
|
2152
|
+
/** The most pieces the outline names: a card with more gets its first ones, which is enough to show how it is built. */
|
|
2153
|
+
const OUTLINE_PIECES = 120;
|
|
2154
|
+
/** Each line of the outline is the start of a title: the outline is read with every piece, so it is kept to a page. */
|
|
2155
|
+
const OUTLINE_LINE_CHARS = 36;
|
|
2156
|
+
function classifyJob(text, tr, card, item, outline) {
|
|
2157
|
+
const header = [
|
|
2158
|
+
tr("Card: {name}", { name: card.name }),
|
|
2159
|
+
tr("Piece: {label}", { label: item.label }),
|
|
2160
|
+
...item.title === "" ? [] : [tr("Title: {title}", { title: item.title })],
|
|
2161
|
+
...item.keys.length === 0 ? [] : [tr("Keys: {keys}", { keys: item.keys.join(", ") })]
|
|
2162
|
+
];
|
|
2163
|
+
return {
|
|
2164
|
+
persona: outline === "" ? text("import/classifier", { max: MAX_TARGETS }) : `${text("import/classifier", { max: MAX_TARGETS })}\n\n${tr("All the pieces of this card, in order:")}\n${outline}`,
|
|
2165
|
+
maxTokens: 2e3,
|
|
2166
|
+
prompt: `${header.join("\n")}\n---\n${item.text.slice(0, SHOWN_CHARS)}`,
|
|
2167
|
+
result: CLASSIFY_SCHEMA,
|
|
2168
|
+
check: (value) => {
|
|
2169
|
+
if (value.roles.length === 0 || value.roles.length > 3 || new Set(value.roles).size !== value.roles.length) return "give one to three different roles";
|
|
2170
|
+
if (value.targets.length > MAX_TARGETS) return `give at most ${MAX_TARGETS} names`;
|
|
2171
|
+
if (value.targets.some((target) => target.name.trim() === "" || target.name.length > MAX_NAME || isPlayerWord(target.name))) return "every name must be a real name of at most 100 characters, and the player is never listed";
|
|
2172
|
+
}
|
|
2173
|
+
};
|
|
2174
|
+
}
|
|
2175
|
+
/** A piece is about the player's own character only when the card says so in terms of the player (its `{{user}}`): a protagonist of the story is not the player. */
|
|
2176
|
+
function playerRoleKept(roles, text) {
|
|
2177
|
+
if (!roles.includes("player") || text.includes("[PLAYER]")) return [...roles];
|
|
2178
|
+
const rest = roles.filter((role) => role !== "player");
|
|
2179
|
+
return rest.length === 0 ? ["character"] : rest;
|
|
2180
|
+
}
|
|
2181
|
+
/**
|
|
2182
|
+
* The role of a piece the decision model is sure is only an instruction, or only notes for the reader: such a piece names nobody, so the language model is not asked.
|
|
2183
|
+
* Anything it is not sure of, or any failure of it, is left to the language model; the decision model is never the only reader of a piece that may be about the story.
|
|
2184
|
+
*/
|
|
2185
|
+
async function settledByDecision(ctx, card, item, problems) {
|
|
2186
|
+
if (ctx.decide === void 0) return void 0;
|
|
2187
|
+
try {
|
|
2188
|
+
const probabilities = await ctx.decide({
|
|
2189
|
+
card: card.name,
|
|
2190
|
+
piece: item.label,
|
|
2191
|
+
...item.title === "" ? {} : { title: item.title },
|
|
2192
|
+
text: item.text.slice(0, SHOWN_CHARS)
|
|
2193
|
+
}, [{
|
|
2194
|
+
key: "instruction",
|
|
2195
|
+
instructions: ctx.text("roleplay/decide-instruction")
|
|
2196
|
+
}, {
|
|
2197
|
+
key: "irrelevant",
|
|
2198
|
+
instructions: ctx.text("roleplay/decide-irrelevant")
|
|
2199
|
+
}]);
|
|
2200
|
+
const sure = yesAt(ctx.confidence ?? .7);
|
|
2201
|
+
if ((probabilities.get("instruction") ?? 0) >= sure) return "instruction";
|
|
2202
|
+
if ((probabilities.get("irrelevant") ?? 0) >= sure) return "irrelevant";
|
|
2203
|
+
} catch (error) {
|
|
2204
|
+
problems.add(error instanceof Error ? error.message : String(error));
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
/** Says what every piece is. A piece that cannot be classified is kept as world background, so that nothing is lost silently; the failures are returned. */
|
|
2208
|
+
async function classifyItems(ctx, card, items) {
|
|
2209
|
+
const outline = items.length < 2 ? "" : items.slice(0, OUTLINE_PIECES).map((piece) => `- ${(piece.title === "" ? piece.label : piece.title).slice(0, OUTLINE_LINE_CHARS)}`).join("\n");
|
|
2210
|
+
const failures = [];
|
|
2211
|
+
const problems = /* @__PURE__ */ new Set();
|
|
2212
|
+
let decided = 0;
|
|
2213
|
+
const answers = await mapLimit(items, ctx.concurrency, async (item, index) => {
|
|
2214
|
+
ctx.say(`classifying ${index + 1}/${items.length}: ${item.label}`);
|
|
2215
|
+
const settled = await settledByDecision(ctx, card, item, problems);
|
|
2216
|
+
if (settled !== void 0) {
|
|
2217
|
+
decided += 1;
|
|
2218
|
+
return {
|
|
2219
|
+
roles: [settled],
|
|
2220
|
+
targets: []
|
|
2221
|
+
};
|
|
2222
|
+
}
|
|
2223
|
+
try {
|
|
2224
|
+
const value = await ctx.run(classifyJob(ctx.text, trOf(ctx), card, item, outline));
|
|
2225
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2226
|
+
const targets = value.targets.map((target) => ({
|
|
2227
|
+
name: withPlayer(target.name.trim()),
|
|
2228
|
+
kind: target.kind
|
|
2229
|
+
})).filter((target) => !isPlayerWord(target.name)).filter((target) => {
|
|
2230
|
+
const id = `${target.kind}:${norm(target.name)}`;
|
|
2231
|
+
if (seen.has(id)) return false;
|
|
2232
|
+
seen.add(id);
|
|
2233
|
+
return true;
|
|
2234
|
+
});
|
|
2235
|
+
return {
|
|
2236
|
+
roles: playerRoleKept(value.roles, item.text),
|
|
2237
|
+
targets
|
|
2238
|
+
};
|
|
2239
|
+
} catch (error) {
|
|
2240
|
+
failures.push(`${item.label}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2241
|
+
return {
|
|
2242
|
+
roles: ["world"],
|
|
2243
|
+
targets: []
|
|
2244
|
+
};
|
|
2245
|
+
}
|
|
2246
|
+
});
|
|
2247
|
+
failures.push(...[...problems].map((problem) => `the decision model could not be used, the language model sorted those pieces: ${problem}`));
|
|
2248
|
+
return {
|
|
2249
|
+
classified: Object.fromEntries(items.map((item, index) => [item.id, answers[index]])),
|
|
2250
|
+
failures,
|
|
2251
|
+
decided
|
|
2252
|
+
};
|
|
2253
|
+
}
|
|
2254
|
+
/** A name that no piece is about becomes an entity only when this many pieces mention it. */
|
|
2255
|
+
const MIN_MENTIONS = 2;
|
|
2256
|
+
/** A name that is only part of one longer name of the same kind (a given name, a short form) is that entity: it is folded into it as an alias. Several longer names make it ambiguous, so it stays. */
|
|
2257
|
+
function foldContained(candidates) {
|
|
2258
|
+
const merged = candidates.map((candidate) => ({
|
|
2259
|
+
candidate,
|
|
2260
|
+
aliases: [],
|
|
2261
|
+
gone: false
|
|
2262
|
+
}));
|
|
2263
|
+
for (const short of merged) {
|
|
2264
|
+
const key = norm(short.candidate.name);
|
|
2265
|
+
if (key.length < 2) continue;
|
|
2266
|
+
const longer = merged.filter((other) => other !== short && !other.gone && other.candidate.kind === short.candidate.kind && norm(other.candidate.name).length > key.length && norm(other.candidate.name).includes(key));
|
|
2267
|
+
if (longer.length !== 1) continue;
|
|
2268
|
+
longer[0].aliases.push(short.candidate.name, ...short.aliases);
|
|
2269
|
+
longer[0].candidate.player ||= short.candidate.player;
|
|
2270
|
+
for (const piece of short.candidate.pieces) if (!longer[0].candidate.pieces.includes(piece)) longer[0].candidate.pieces.push(piece);
|
|
2271
|
+
short.gone = true;
|
|
2272
|
+
}
|
|
2273
|
+
return merged.filter((entry) => !entry.gone).map(({ candidate, aliases }) => ({
|
|
2274
|
+
candidate,
|
|
2275
|
+
aliases
|
|
2276
|
+
}));
|
|
2277
|
+
}
|
|
2278
|
+
/** The names the pieces are about, by kind: the same name in different spellings of case or punctuation is one. */
|
|
2279
|
+
function candidatesOf(items, classified) {
|
|
2280
|
+
const found = /* @__PURE__ */ new Map();
|
|
2281
|
+
for (const item of items) {
|
|
2282
|
+
const classification = classified[item.id];
|
|
2283
|
+
if (classification === void 0) continue;
|
|
2284
|
+
if (isLeftOut(classification) || isGeneratorOnly(classification)) continue;
|
|
2285
|
+
classification.targets.forEach(({ name, kind }, index) => {
|
|
2286
|
+
if (kind === "other" || norm(name) === "") return;
|
|
2287
|
+
const id = `${kind}:${norm(name)}`;
|
|
2288
|
+
const candidate = found.get(id) ?? {
|
|
2289
|
+
kind,
|
|
2290
|
+
name,
|
|
2291
|
+
player: false,
|
|
2292
|
+
pieces: [],
|
|
2293
|
+
titles: [],
|
|
2294
|
+
primary: false
|
|
2295
|
+
};
|
|
2296
|
+
candidate.primary ||= index === 0 || kind === "place" && (playsRole(classification, "place") || playsRole(classification, "scenario"));
|
|
2297
|
+
candidate.player ||= kind === "character" && playsRole(classification, "player");
|
|
2298
|
+
if (!candidate.pieces.includes(item.id)) {
|
|
2299
|
+
candidate.pieces.push(item.id);
|
|
2300
|
+
if (item.title !== "" && candidate.titles.length < 2) candidate.titles.push(item.title);
|
|
2301
|
+
}
|
|
2302
|
+
found.set(id, candidate);
|
|
2303
|
+
});
|
|
2304
|
+
}
|
|
2305
|
+
return [...found.values()].filter((candidate) => candidate.primary || candidate.player || candidate.pieces.length >= MIN_MENTIONS);
|
|
2306
|
+
}
|
|
2307
|
+
const ENTRY = (extra = {}) => ({
|
|
2308
|
+
type: "object",
|
|
2309
|
+
properties: {
|
|
2310
|
+
name: { type: "string" },
|
|
2311
|
+
aliases: {
|
|
2312
|
+
type: "array",
|
|
2313
|
+
items: { type: "string" }
|
|
2314
|
+
},
|
|
2315
|
+
...extra
|
|
2316
|
+
},
|
|
2317
|
+
required: ["name", "aliases"],
|
|
2318
|
+
additionalProperties: false
|
|
2319
|
+
});
|
|
2320
|
+
const ROSTER_SCHEMA = {
|
|
2321
|
+
type: "object",
|
|
2322
|
+
properties: {
|
|
2323
|
+
characters: {
|
|
2324
|
+
type: "array",
|
|
2325
|
+
items: ENTRY({ player: {
|
|
2326
|
+
type: "boolean",
|
|
2327
|
+
description: "True for the character the player plays; at most one."
|
|
2328
|
+
} })
|
|
2329
|
+
},
|
|
2330
|
+
places: {
|
|
2331
|
+
type: "array",
|
|
2332
|
+
items: ENTRY({ parent: {
|
|
2333
|
+
type: "string",
|
|
2334
|
+
description: "The main name of the place this one is in, when it is in one."
|
|
2335
|
+
} })
|
|
2336
|
+
},
|
|
2337
|
+
factions: {
|
|
2338
|
+
type: "array",
|
|
2339
|
+
items: ENTRY()
|
|
2340
|
+
},
|
|
2341
|
+
things: {
|
|
2342
|
+
type: "array",
|
|
2343
|
+
items: ENTRY()
|
|
2344
|
+
}
|
|
2345
|
+
},
|
|
2346
|
+
required: [
|
|
2347
|
+
"characters",
|
|
2348
|
+
"places",
|
|
2349
|
+
"factions",
|
|
2350
|
+
"things"
|
|
2351
|
+
],
|
|
2352
|
+
additionalProperties: false
|
|
2353
|
+
};
|
|
2354
|
+
const MAX_ENTITIES = 200;
|
|
2355
|
+
function rosterCheck(answer) {
|
|
2356
|
+
const all = [
|
|
2357
|
+
...answer.characters,
|
|
2358
|
+
...answer.places,
|
|
2359
|
+
...answer.factions,
|
|
2360
|
+
...answer.things
|
|
2361
|
+
];
|
|
2362
|
+
if (all.length > MAX_ENTITIES) return `the list has ${all.length} entries; at most ${MAX_ENTITIES}`;
|
|
2363
|
+
if (all.some((entry) => entry.name.trim() === "" || entry.name.length > MAX_NAME || /\[PLAYER\]|\{\{\s*user\s*\}\}/i.test(entry.name))) return "every entry needs a real name of at most 100 characters, and the player is never listed";
|
|
2364
|
+
for (const [kind, list] of [
|
|
2365
|
+
["characters", answer.characters],
|
|
2366
|
+
["places", answer.places],
|
|
2367
|
+
["factions", answer.factions],
|
|
2368
|
+
["things", answer.things]
|
|
2369
|
+
]) {
|
|
2370
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2371
|
+
for (const entry of list) {
|
|
2372
|
+
if (seen.has(norm(entry.name))) return `${kind}: "${entry.name}" is listed twice: merge it`;
|
|
2373
|
+
seen.add(norm(entry.name));
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
if (answer.characters.filter((entry) => entry.player === true).length > 1) return "at most one character is the player";
|
|
2377
|
+
}
|
|
2378
|
+
function rosterJob(text, tr, card, candidates, titleIsBeing) {
|
|
2379
|
+
const lines = candidates.map((candidate) => `${candidate.kind}: ${candidate.name} (${tr("{count} pieces", { count: candidate.pieces.length })}${candidate.player ? `, ${tr("about the player's character")}` : ""}${candidate.titles.length === 0 ? "" : `; ${tr("titles: {titles}", { titles: candidate.titles.join(" / ") })}`})`);
|
|
2380
|
+
return {
|
|
2381
|
+
persona: text("import/roster"),
|
|
2382
|
+
maxTokens: 8e3,
|
|
2383
|
+
prompt: `${tr("Card title: {name}", { name: card.name })}\n${titleIsBeing}\n\n${tr("Names found:")}\n${lines.join("\n")}`,
|
|
2384
|
+
result: ROSTER_SCHEMA,
|
|
2385
|
+
check: rosterCheck
|
|
2386
|
+
};
|
|
2387
|
+
}
|
|
2388
|
+
/** Names that the text gives for one another in brackets ("A (also called B)"): the second is folded into the first when both are listed as the same kind. */
|
|
2389
|
+
function foldNamedAliases(answer, text) {
|
|
2390
|
+
const flat = text.normalize("NFKC");
|
|
2391
|
+
const escape = (value) => value.normalize("NFKC").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2392
|
+
for (const list of [
|
|
2393
|
+
answer.characters,
|
|
2394
|
+
answer.places,
|
|
2395
|
+
answer.factions,
|
|
2396
|
+
answer.things
|
|
2397
|
+
]) for (let i = 0; i < list.length; i += 1) for (let j = list.length - 1; j >= 0; j -= 1) {
|
|
2398
|
+
if (i === j || list[i] === void 0 || list[j] === void 0 || norm(list[j].name).length < 2 || norm(list[i].name).length < 2) continue;
|
|
2399
|
+
const known = (entry) => [entry.name, ...entry.aliases].filter((name) => norm(name).length >= 2);
|
|
2400
|
+
if (!known(list[i]).some((first) => known(list[j]).some((second) => new RegExp(`${escape(first)}\\s*[((][^))]{0,14}${escape(second)}\\s*[))]`).test(flat)))) continue;
|
|
2401
|
+
list[i].aliases.push(list[j].name, ...list[j].aliases);
|
|
2402
|
+
if (list[j].player === true) list[i].player = true;
|
|
2403
|
+
list.splice(j, 1);
|
|
2404
|
+
if (j < i) i -= 1;
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
/**
|
|
2408
|
+
* The list of everyone and everything the world is made of, keyed for the world's files. The names found in the pieces are merged by one call; when it fails
|
|
2409
|
+
* the names stand as found. The card's own title is a candidate too when the description is about a being by that name.
|
|
2410
|
+
*/
|
|
2411
|
+
async function buildRoster(ctx, card, items, classified) {
|
|
2412
|
+
const candidates = candidatesOf(items, classified);
|
|
2413
|
+
const tr = trOf(ctx);
|
|
2414
|
+
const titleIsBeing = candidates.some((candidate) => candidate.kind === "character" && norm(candidate.name) === norm(card.name)) ? tr("The pieces name the card title as a character.") : tr("The card title is not named as a character by any piece.");
|
|
2415
|
+
let answer;
|
|
2416
|
+
let failure;
|
|
2417
|
+
try {
|
|
2418
|
+
answer = candidates.length === 0 ? {
|
|
2419
|
+
characters: [],
|
|
2420
|
+
places: [],
|
|
2421
|
+
factions: [],
|
|
2422
|
+
things: []
|
|
2423
|
+
} : await ctx.run(rosterJob(ctx.text, tr, card, candidates, titleIsBeing));
|
|
2424
|
+
} catch (error) {
|
|
2425
|
+
failure = `the list of names could not be merged: ${error instanceof Error ? error.message : String(error)}`;
|
|
2426
|
+
const folded = foldContained(candidates.map((candidate) => ({
|
|
2427
|
+
...candidate,
|
|
2428
|
+
pieces: [...candidate.pieces]
|
|
2429
|
+
})));
|
|
2430
|
+
const as = (kind) => folded.filter((entry) => entry.candidate.kind === kind).map((entry) => ({
|
|
2431
|
+
name: entry.candidate.name,
|
|
2432
|
+
aliases: entry.aliases,
|
|
2433
|
+
...kind === "character" ? { player: entry.candidate.player } : {}
|
|
2434
|
+
}));
|
|
2435
|
+
answer = {
|
|
2436
|
+
characters: as("character"),
|
|
2437
|
+
places: as("place"),
|
|
2438
|
+
factions: as("faction"),
|
|
2439
|
+
things: as("thing")
|
|
2440
|
+
};
|
|
2441
|
+
}
|
|
2442
|
+
foldNamedAliases(answer, items.map((item) => item.text).join("\n"));
|
|
2443
|
+
const supplied = new Set(candidates.filter((candidate) => candidate.player).flatMap((candidate) => [candidate.name, ...answer.characters.filter((entry) => norm(entry.name) === norm(candidate.name)).flatMap((entry) => entry.aliases)]).map(norm));
|
|
2444
|
+
for (const entry of answer.characters) if (entry.player === true && ![entry.name, ...entry.aliases].some((name) => supplied.has(norm(name)))) entry.player = false;
|
|
2445
|
+
const taken = /* @__PURE__ */ new Set();
|
|
2446
|
+
const entities = [];
|
|
2447
|
+
const add = (kind, entry) => {
|
|
2448
|
+
const name = entry.name.trim();
|
|
2449
|
+
entities.push({
|
|
2450
|
+
kind,
|
|
2451
|
+
key: uniqueKey(slug(name, kind), taken),
|
|
2452
|
+
name,
|
|
2453
|
+
aliases: [...new Set(entry.aliases.map((alias) => alias.trim()).filter((alias) => alias !== "" && norm(alias) !== norm(name)))],
|
|
2454
|
+
player: kind === "character" && entry.player === true,
|
|
2455
|
+
...entry.parent === void 0 || entry.parent.trim() === "" ? {} : { parent: entry.parent.trim() }
|
|
2456
|
+
});
|
|
2457
|
+
};
|
|
2458
|
+
for (const entry of answer.characters) add("character", entry);
|
|
2459
|
+
for (const entry of answer.places) add("place", entry);
|
|
2460
|
+
for (const entry of answer.factions) add("faction", entry);
|
|
2461
|
+
for (const entry of answer.things) add("thing", entry);
|
|
2462
|
+
return {
|
|
2463
|
+
roster: entities,
|
|
2464
|
+
...failure === void 0 ? {} : { failure }
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
/** The entity a name stands for: by its name or an alias, the same when compared as names; otherwise one that contains it or is contained by it, when that is unambiguous. */
|
|
2468
|
+
function findEntity(roster, name, kind) {
|
|
2469
|
+
const wanted = norm(name);
|
|
2470
|
+
if (wanted === "") return void 0;
|
|
2471
|
+
const pool = roster.filter((entity) => kind === void 0 || entity.kind === kind);
|
|
2472
|
+
const exact = pool.find((entity) => [entity.name, ...entity.aliases].some((candidate) => norm(candidate) === wanted));
|
|
2473
|
+
if (exact !== void 0) return exact;
|
|
2474
|
+
if (wanted.length < 2) return void 0;
|
|
2475
|
+
const near = pool.filter((entity) => [entity.name, ...entity.aliases].some((candidate) => {
|
|
2476
|
+
const other = norm(candidate);
|
|
2477
|
+
return other.length >= 2 && (other.includes(wanted) || wanted.includes(other));
|
|
2478
|
+
}));
|
|
2479
|
+
return near.length === 1 ? near[0] : void 0;
|
|
2480
|
+
}
|
|
2481
|
+
//#endregion
|
|
2482
|
+
//#region src/host/import/extract.ts
|
|
2483
|
+
const emptyExtracted = () => ({
|
|
2484
|
+
characters: [],
|
|
2485
|
+
locations: [],
|
|
2486
|
+
factions: [],
|
|
2487
|
+
items: [],
|
|
2488
|
+
lore: [],
|
|
2489
|
+
prompts: [],
|
|
2490
|
+
variables: [],
|
|
2491
|
+
casting: [],
|
|
2492
|
+
commands: [],
|
|
2493
|
+
triggers: [],
|
|
2494
|
+
notes: []
|
|
2495
|
+
});
|
|
2496
|
+
const SOURCE_BUDGET_CHARS = 14e3;
|
|
2497
|
+
const MAX_TAGGED = 8;
|
|
2498
|
+
const MAX_MENTIONS = 6;
|
|
2499
|
+
const MIN_MENTION_CHARS = 2;
|
|
2500
|
+
const text = (value) => typeof value === "string" ? value.trim() : "";
|
|
2501
|
+
const list = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() !== "" ? [entry.trim()] : []) : [];
|
|
2502
|
+
const objects = (value) => Array.isArray(value) ? value.filter((entry) => typeof entry === "object" && entry !== null && !Array.isArray(entry)) : [];
|
|
2503
|
+
const put = (document, key, value) => {
|
|
2504
|
+
if (value !== void 0 && value !== "" && !(Array.isArray(value) && value.length === 0)) document[key] = value;
|
|
2505
|
+
};
|
|
2506
|
+
/** The pieces an entity is made from: the ones about it, then others that name it, within a budget of text. */
|
|
2507
|
+
function sourcesFor(entity, items, classified) {
|
|
2508
|
+
const names = [entity.name, ...entity.aliases].map(norm).filter((name) => name.length >= MIN_MENTION_CHARS);
|
|
2509
|
+
const about = (item) => (classified[item.id]?.targets ?? []).some((target) => target.kind === entity.kind && names.includes(norm(target.name)));
|
|
2510
|
+
const tagged = items.filter((item) => about(item) && !isLeftOut(classified[item.id] ?? {
|
|
2511
|
+
roles: [],
|
|
2512
|
+
targets: []
|
|
2513
|
+
})).slice(0, MAX_TAGGED);
|
|
2514
|
+
const taken = new Set(tagged.map((item) => item.id));
|
|
2515
|
+
const mentions = items.filter((item) => !taken.has(item.id) && !isLeftOut(classified[item.id] ?? {
|
|
2516
|
+
roles: ["world"],
|
|
2517
|
+
targets: []
|
|
2518
|
+
}) && names.some((name) => norm(item.text).includes(name))).slice(0, MAX_MENTIONS);
|
|
2519
|
+
const chosen = [];
|
|
2520
|
+
let used = 0;
|
|
2521
|
+
for (const item of [...tagged, ...mentions]) {
|
|
2522
|
+
if (used + item.text.length > SOURCE_BUDGET_CHARS && chosen.length > 0) continue;
|
|
2523
|
+
chosen.push(item);
|
|
2524
|
+
used += item.text.length;
|
|
2525
|
+
}
|
|
2526
|
+
return chosen;
|
|
2527
|
+
}
|
|
2528
|
+
const rosterLines = (roster, tr) => [
|
|
2529
|
+
["character", tr("characters")],
|
|
2530
|
+
["place", tr("places")],
|
|
2531
|
+
["faction", tr("factions")],
|
|
2532
|
+
["thing", tr("things")]
|
|
2533
|
+
].map(([kind, label]) => `${label}: ${roster.filter((entity) => entity.kind === kind).map((entity) => entity.name).join("; ") || tr("(none)")}`).join("\n");
|
|
2534
|
+
function promptFor(entity, sources, roster, card, tr) {
|
|
2535
|
+
const pieces = sources.map((source) => `[${source.label}]${source.title === "" ? "" : ` ${source.title}`}\n${source.text}`);
|
|
2536
|
+
const made = entity.player ? tr("Make the {kind} that the player plays: {name}", {
|
|
2537
|
+
kind: entity.kind,
|
|
2538
|
+
name: entity.name
|
|
2539
|
+
}) : tr("Make the {kind}: {name}", {
|
|
2540
|
+
kind: entity.kind,
|
|
2541
|
+
name: entity.name
|
|
2542
|
+
});
|
|
2543
|
+
return [
|
|
2544
|
+
tr("Card: {name}", { name: card.name }),
|
|
2545
|
+
`${made}${entity.aliases.length === 0 ? "" : ` ${tr("(also called: {names})", { names: entity.aliases.join(", ") })}`}`,
|
|
2546
|
+
`${tr("The others in this world, which are the only ones you may refer to:")}\n${rosterLines(roster, tr)}`,
|
|
2547
|
+
`${tr("Source pieces:")}\n${pieces.length === 0 ? tr("(none: write only what the name itself implies, and leave the rest empty)") : pieces.join("\n\n---\n\n")}`
|
|
2548
|
+
].join("\n\n");
|
|
2549
|
+
}
|
|
2550
|
+
const str = (description) => ({
|
|
2551
|
+
type: "string",
|
|
2552
|
+
description
|
|
2553
|
+
});
|
|
2554
|
+
const strs = (description) => ({
|
|
2555
|
+
type: "array",
|
|
2556
|
+
items: { type: "string" },
|
|
2557
|
+
description
|
|
2558
|
+
});
|
|
2559
|
+
const CHARACTER_SCHEMA = {
|
|
2560
|
+
type: "object",
|
|
2561
|
+
properties: {
|
|
2562
|
+
aliases: strs("Other names they go by."),
|
|
2563
|
+
age: str("As the pieces say it."),
|
|
2564
|
+
gender: str(""),
|
|
2565
|
+
pronouns: str(""),
|
|
2566
|
+
tier: {
|
|
2567
|
+
type: "string",
|
|
2568
|
+
enum: [...CHARACTER_TIERS]
|
|
2569
|
+
},
|
|
2570
|
+
kind: {
|
|
2571
|
+
type: "string",
|
|
2572
|
+
enum: [...CHARACTER_KINDS]
|
|
2573
|
+
},
|
|
2574
|
+
summary: str("One or two sentences."),
|
|
2575
|
+
personality: str(""),
|
|
2576
|
+
background: str(""),
|
|
2577
|
+
appearance: str(""),
|
|
2578
|
+
speech: {
|
|
2579
|
+
type: "object",
|
|
2580
|
+
properties: {
|
|
2581
|
+
style: str(""),
|
|
2582
|
+
examples: strs("Up to eight lines.")
|
|
2583
|
+
},
|
|
2584
|
+
required: ["style", "examples"],
|
|
2585
|
+
additionalProperties: false
|
|
2586
|
+
},
|
|
2587
|
+
start: {
|
|
2588
|
+
type: "object",
|
|
2589
|
+
properties: {
|
|
2590
|
+
public_state: str(""),
|
|
2591
|
+
inner_state: str(""),
|
|
2592
|
+
activity: str(""),
|
|
2593
|
+
location: str("A name from the list of places."),
|
|
2594
|
+
position: str("")
|
|
2595
|
+
},
|
|
2596
|
+
additionalProperties: false
|
|
2597
|
+
},
|
|
2598
|
+
goals: {
|
|
2599
|
+
type: "array",
|
|
2600
|
+
items: {
|
|
2601
|
+
type: "object",
|
|
2602
|
+
properties: {
|
|
2603
|
+
name: str(""),
|
|
2604
|
+
description: str("")
|
|
2605
|
+
},
|
|
2606
|
+
required: ["name"],
|
|
2607
|
+
additionalProperties: false
|
|
2608
|
+
}
|
|
2609
|
+
},
|
|
2610
|
+
relationships: {
|
|
2611
|
+
type: "array",
|
|
2612
|
+
items: {
|
|
2613
|
+
type: "object",
|
|
2614
|
+
properties: {
|
|
2615
|
+
with: str("A name from the list of characters."),
|
|
2616
|
+
label: str(""),
|
|
2617
|
+
summary: str("")
|
|
2618
|
+
},
|
|
2619
|
+
required: ["with", "label"],
|
|
2620
|
+
additionalProperties: false
|
|
2621
|
+
}
|
|
2622
|
+
},
|
|
2623
|
+
knows: {
|
|
2624
|
+
type: "object",
|
|
2625
|
+
properties: {
|
|
2626
|
+
places: strs("Names from the list of places that they know of."),
|
|
2627
|
+
things: strs("Names from the list of things that they know of."),
|
|
2628
|
+
ways: {
|
|
2629
|
+
type: "array",
|
|
2630
|
+
items: {
|
|
2631
|
+
type: "object",
|
|
2632
|
+
properties: {
|
|
2633
|
+
from: str("A name from the list of places."),
|
|
2634
|
+
to: str("A name from the list of places.")
|
|
2635
|
+
},
|
|
2636
|
+
required: ["from", "to"],
|
|
2637
|
+
additionalProperties: false
|
|
2638
|
+
},
|
|
2639
|
+
description: "Ways between two places of the list that they know how to take (the way from one to the other)."
|
|
2640
|
+
}
|
|
2641
|
+
},
|
|
2642
|
+
additionalProperties: false
|
|
2643
|
+
}
|
|
2644
|
+
},
|
|
2645
|
+
required: [
|
|
2646
|
+
"tier",
|
|
2647
|
+
"kind",
|
|
2648
|
+
"summary",
|
|
2649
|
+
"personality",
|
|
2650
|
+
"background",
|
|
2651
|
+
"appearance",
|
|
2652
|
+
"speech"
|
|
2653
|
+
],
|
|
2654
|
+
additionalProperties: false
|
|
2655
|
+
};
|
|
2656
|
+
/** The document of a character file from what the call answered; names of places and characters become the keys they have in the roster. */
|
|
2657
|
+
function characterDocument(entity, answer, roster) {
|
|
2658
|
+
const notes = [];
|
|
2659
|
+
const document = {
|
|
2660
|
+
id: entity.key,
|
|
2661
|
+
name: entity.name
|
|
2662
|
+
};
|
|
2663
|
+
put(document, "aliases", [.../* @__PURE__ */ new Set([...entity.aliases, ...list(answer["aliases"])])].filter((alias) => norm(alias) !== norm(entity.name)));
|
|
2664
|
+
for (const field of [
|
|
2665
|
+
"age",
|
|
2666
|
+
"gender",
|
|
2667
|
+
"pronouns"
|
|
2668
|
+
]) put(document, field, text(answer[field]));
|
|
2669
|
+
const playable = entity.player;
|
|
2670
|
+
const group = answer["kind"] === "group" && !playable;
|
|
2671
|
+
document["role"] = playable ? "playable" : "npc";
|
|
2672
|
+
document["kind"] = group ? "group" : "person";
|
|
2673
|
+
document["tier"] = playable && answer["tier"] === "background" ? "principal" : CHARACTER_TIERS.includes(answer["tier"]) ? answer["tier"] : "supporting";
|
|
2674
|
+
for (const field of [
|
|
2675
|
+
"summary",
|
|
2676
|
+
"personality",
|
|
2677
|
+
"background",
|
|
2678
|
+
"appearance"
|
|
2679
|
+
]) document[field] = text(answer[field]);
|
|
2680
|
+
const speech = typeof answer["speech"] === "object" && answer["speech"] !== null ? answer["speech"] : {};
|
|
2681
|
+
document["speech"] = {
|
|
2682
|
+
style: text(speech["style"]),
|
|
2683
|
+
examples: list(speech["examples"]).slice(0, 8)
|
|
2684
|
+
};
|
|
2685
|
+
const start = {};
|
|
2686
|
+
const given = typeof answer["start"] === "object" && answer["start"] !== null ? answer["start"] : {};
|
|
2687
|
+
for (const [from, to] of [
|
|
2688
|
+
["public_state", "public_state"],
|
|
2689
|
+
["inner_state", "inner_state"],
|
|
2690
|
+
["activity", "activity"]
|
|
2691
|
+
]) put(start, to, text(given[from]));
|
|
2692
|
+
const place = text(given["location"]) === "" ? void 0 : findEntity(roster, text(given["location"]), "place");
|
|
2693
|
+
if (text(given["location"]) !== "" && place === void 0) notes.push(`${entity.name}: the place "${text(given["location"])}" is not one of the world's places, so the character starts nowhere`);
|
|
2694
|
+
if (place !== void 0) {
|
|
2695
|
+
start["location"] = place.key;
|
|
2696
|
+
put(start, "position", text(given["position"]));
|
|
2697
|
+
}
|
|
2698
|
+
const goals = objects(answer["goals"]).filter((goal) => text(goal["name"]) !== "").map((goal) => ({
|
|
2699
|
+
type: "agenda",
|
|
2700
|
+
name: text(goal["name"]),
|
|
2701
|
+
...text(goal["description"]) === "" ? {} : { description: text(goal["description"]) },
|
|
2702
|
+
status: "active"
|
|
2703
|
+
}));
|
|
2704
|
+
put(start, "intents", goals);
|
|
2705
|
+
document["start"] = start;
|
|
2706
|
+
const seen = /* @__PURE__ */ new Set([entity.key]);
|
|
2707
|
+
const relationships = [];
|
|
2708
|
+
for (const relation of objects(answer["relationships"])) {
|
|
2709
|
+
const other = findEntity(roster, text(relation["with"]), "character");
|
|
2710
|
+
if (other === void 0) {
|
|
2711
|
+
notes.push(`${entity.name}: the relationship with "${text(relation["with"])}" names nobody in the world`);
|
|
2712
|
+
continue;
|
|
2713
|
+
}
|
|
2714
|
+
if (seen.has(other.key) || text(relation["label"]) === "") continue;
|
|
2715
|
+
seen.add(other.key);
|
|
2716
|
+
relationships.push({
|
|
2717
|
+
to: other.key,
|
|
2718
|
+
label: text(relation["label"]),
|
|
2719
|
+
...text(relation["summary"]) === "" ? {} : { summary: text(relation["summary"]) }
|
|
2720
|
+
});
|
|
2721
|
+
}
|
|
2722
|
+
put(document, "relationships", relationships.slice(0, 60));
|
|
2723
|
+
const knows = typeof answer["knows"] === "object" && answer["knows"] !== null ? answer["knows"] : {};
|
|
2724
|
+
const known = (names, kind) => [...new Set(names.flatMap((name) => {
|
|
2725
|
+
const found = findEntity(roster, name, kind);
|
|
2726
|
+
if (found === void 0) notes.push(`${entity.name}: "${name}" is not one of the world's ${kind === "place" ? "places" : "things"}, so they do not know of it`);
|
|
2727
|
+
return found === void 0 ? [] : [found.key];
|
|
2728
|
+
}))];
|
|
2729
|
+
const knowledge = {};
|
|
2730
|
+
put(knowledge, "locations", known(list(knows["places"]), "place"));
|
|
2731
|
+
put(knowledge, "items", known(list(knows["things"]), "thing"));
|
|
2732
|
+
const ways = /* @__PURE__ */ new Set();
|
|
2733
|
+
const exits = [];
|
|
2734
|
+
for (const way of objects(knows["ways"])) {
|
|
2735
|
+
const from = findEntity(roster, text(way["from"]), "place");
|
|
2736
|
+
const to = findEntity(roster, text(way["to"]), "place");
|
|
2737
|
+
if (from === void 0 || to === void 0 || from.key === to.key) {
|
|
2738
|
+
notes.push(`${entity.name}: the way from "${text(way["from"])}" to "${text(way["to"])}" is not between two places of the world, so they do not know of it`);
|
|
2739
|
+
continue;
|
|
2740
|
+
}
|
|
2741
|
+
if (ways.has(`${from.key}>${to.key}`)) continue;
|
|
2742
|
+
ways.add(`${from.key}>${to.key}`);
|
|
2743
|
+
exits.push({
|
|
2744
|
+
from: from.key,
|
|
2745
|
+
to: to.key
|
|
2746
|
+
});
|
|
2747
|
+
}
|
|
2748
|
+
put(knowledge, "exits", exits);
|
|
2749
|
+
put(document, "knowledge", Object.keys(knowledge).length === 0 ? void 0 : knowledge);
|
|
2750
|
+
return {
|
|
2751
|
+
document,
|
|
2752
|
+
notes
|
|
2753
|
+
};
|
|
2754
|
+
}
|
|
2755
|
+
const PLACE_SCHEMA = {
|
|
2756
|
+
type: "object",
|
|
2757
|
+
properties: {
|
|
2758
|
+
description: str("What the place is like."),
|
|
2759
|
+
parent: str("A name from the list of places."),
|
|
2760
|
+
features: {
|
|
2761
|
+
type: "array",
|
|
2762
|
+
items: {
|
|
2763
|
+
type: "object",
|
|
2764
|
+
properties: {
|
|
2765
|
+
name: str(""),
|
|
2766
|
+
description: str("")
|
|
2767
|
+
},
|
|
2768
|
+
required: ["name"],
|
|
2769
|
+
additionalProperties: false
|
|
2770
|
+
}
|
|
2771
|
+
},
|
|
2772
|
+
exits: {
|
|
2773
|
+
type: "array",
|
|
2774
|
+
items: {
|
|
2775
|
+
type: "object",
|
|
2776
|
+
properties: {
|
|
2777
|
+
to: str("A name from the list of places."),
|
|
2778
|
+
description: str("")
|
|
2779
|
+
},
|
|
2780
|
+
required: ["to"],
|
|
2781
|
+
additionalProperties: false
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
},
|
|
2785
|
+
required: ["description"],
|
|
2786
|
+
additionalProperties: false
|
|
2787
|
+
};
|
|
2788
|
+
function placeDocument(entity, answer, roster) {
|
|
2789
|
+
const notes = [];
|
|
2790
|
+
const document = {
|
|
2791
|
+
id: entity.key,
|
|
2792
|
+
name: entity.name
|
|
2793
|
+
};
|
|
2794
|
+
put(document, "description", text(answer["description"]));
|
|
2795
|
+
const named = text(answer["parent"]) === "" ? entity.parent : text(answer["parent"]);
|
|
2796
|
+
const parent = named === void 0 ? void 0 : findEntity(roster, named, "place");
|
|
2797
|
+
if (named !== void 0 && (parent === void 0 || parent.key === entity.key)) notes.push(`${entity.name}: the place it is in, "${named}", is not one of the world's places`);
|
|
2798
|
+
if (parent !== void 0 && parent.key !== entity.key) document["parent"] = parent.key;
|
|
2799
|
+
const features = objects(answer["features"]).filter((feature) => text(feature["name"]) !== "").slice(0, 30).map((feature, index) => ({
|
|
2800
|
+
id: `feature-${index + 1}`,
|
|
2801
|
+
name: text(feature["name"]),
|
|
2802
|
+
...text(feature["description"]) === "" ? {} : { description: text(feature["description"]) }
|
|
2803
|
+
}));
|
|
2804
|
+
put(document, "features", features);
|
|
2805
|
+
const exits = [];
|
|
2806
|
+
const to = /* @__PURE__ */ new Set();
|
|
2807
|
+
for (const exit of objects(answer["exits"])) {
|
|
2808
|
+
const target = findEntity(roster, text(exit["to"]), "place");
|
|
2809
|
+
if (target === void 0 || target.key === entity.key) {
|
|
2810
|
+
notes.push(`${entity.name}: the way to "${text(exit["to"])}" leads to no place of the world`);
|
|
2811
|
+
continue;
|
|
2812
|
+
}
|
|
2813
|
+
if (to.has(target.key)) continue;
|
|
2814
|
+
to.add(target.key);
|
|
2815
|
+
exits.push({
|
|
2816
|
+
to: target.key,
|
|
2817
|
+
...text(exit["description"]) === "" ? {} : { description: text(exit["description"]) }
|
|
2818
|
+
});
|
|
2819
|
+
}
|
|
2820
|
+
put(document, "exits", exits.slice(0, 30));
|
|
2821
|
+
return {
|
|
2822
|
+
document,
|
|
2823
|
+
notes
|
|
2824
|
+
};
|
|
2825
|
+
}
|
|
2826
|
+
const FACTION_SCHEMA = {
|
|
2827
|
+
type: "object",
|
|
2828
|
+
properties: {
|
|
2829
|
+
aliases: strs("Other names for it."),
|
|
2830
|
+
summary: str(""),
|
|
2831
|
+
description: str(""),
|
|
2832
|
+
values: strs("Principles it claims."),
|
|
2833
|
+
structure: str(""),
|
|
2834
|
+
public_state: str(""),
|
|
2835
|
+
inner_state: str(""),
|
|
2836
|
+
members: {
|
|
2837
|
+
type: "array",
|
|
2838
|
+
items: {
|
|
2839
|
+
type: "object",
|
|
2840
|
+
properties: {
|
|
2841
|
+
character: str("A name from the list of characters."),
|
|
2842
|
+
role: str("")
|
|
2843
|
+
},
|
|
2844
|
+
required: ["character"],
|
|
2845
|
+
additionalProperties: false
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
},
|
|
2849
|
+
required: ["summary", "description"],
|
|
2850
|
+
additionalProperties: false
|
|
2851
|
+
};
|
|
2852
|
+
function factionDocument(entity, answer, roster) {
|
|
2853
|
+
const notes = [];
|
|
2854
|
+
const document = {
|
|
2855
|
+
id: entity.key,
|
|
2856
|
+
name: entity.name
|
|
2857
|
+
};
|
|
2858
|
+
put(document, "aliases", [.../* @__PURE__ */ new Set([...entity.aliases, ...list(answer["aliases"])])].filter((alias) => norm(alias) !== norm(entity.name)));
|
|
2859
|
+
for (const field of [
|
|
2860
|
+
"summary",
|
|
2861
|
+
"description",
|
|
2862
|
+
"structure"
|
|
2863
|
+
]) put(document, field, text(answer[field]));
|
|
2864
|
+
put(document, "values", list(answer["values"]));
|
|
2865
|
+
const start = {};
|
|
2866
|
+
put(start, "public_state", text(answer["public_state"]));
|
|
2867
|
+
put(start, "inner_state", text(answer["inner_state"]));
|
|
2868
|
+
put(document, "start", Object.keys(start).length === 0 ? void 0 : start);
|
|
2869
|
+
const members = [];
|
|
2870
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2871
|
+
for (const member of objects(answer["members"])) {
|
|
2872
|
+
const character = findEntity(roster, text(member["character"]), "character");
|
|
2873
|
+
if (character === void 0) {
|
|
2874
|
+
notes.push(`${entity.name}: the member "${text(member["character"])}" is nobody in the world`);
|
|
2875
|
+
continue;
|
|
2876
|
+
}
|
|
2877
|
+
if (seen.has(character.key)) continue;
|
|
2878
|
+
seen.add(character.key);
|
|
2879
|
+
members.push({
|
|
2880
|
+
character: character.key,
|
|
2881
|
+
...text(member["role"]) === "" ? {} : { role: text(member["role"]) }
|
|
2882
|
+
});
|
|
2883
|
+
}
|
|
2884
|
+
put(document, "members", members);
|
|
2885
|
+
return {
|
|
2886
|
+
document,
|
|
2887
|
+
notes
|
|
2888
|
+
};
|
|
2889
|
+
}
|
|
2890
|
+
const THING_SCHEMA = {
|
|
2891
|
+
type: "object",
|
|
2892
|
+
properties: {
|
|
2893
|
+
description: str(""),
|
|
2894
|
+
quality: str(""),
|
|
2895
|
+
notable: { type: "boolean" },
|
|
2896
|
+
location: str("A name from the list of places."),
|
|
2897
|
+
held_by: str("A name from the list of characters.")
|
|
2898
|
+
},
|
|
2899
|
+
required: ["description"],
|
|
2900
|
+
additionalProperties: false
|
|
2901
|
+
};
|
|
2902
|
+
function thingDocument(entity, answer, roster) {
|
|
2903
|
+
const notes = [];
|
|
2904
|
+
const document = {
|
|
2905
|
+
id: entity.key,
|
|
2906
|
+
name: entity.name,
|
|
2907
|
+
unique: true
|
|
2908
|
+
};
|
|
2909
|
+
put(document, "description", text(answer["description"]));
|
|
2910
|
+
put(document, "quality", text(answer["quality"]));
|
|
2911
|
+
if (answer["notable"] === true) document["notable"] = true;
|
|
2912
|
+
const holder = text(answer["held_by"]) === "" ? void 0 : findEntity(roster, text(answer["held_by"]), "character");
|
|
2913
|
+
const place = text(answer["location"]) === "" ? void 0 : findEntity(roster, text(answer["location"]), "place");
|
|
2914
|
+
if (holder !== void 0) document["held_by"] = holder.key;
|
|
2915
|
+
else if (place !== void 0) document["location"] = place.key;
|
|
2916
|
+
else notes.push(`${entity.name}: it is nowhere in the world and nobody has it, so it is left out`);
|
|
2917
|
+
return {
|
|
2918
|
+
document,
|
|
2919
|
+
notes
|
|
2920
|
+
};
|
|
2921
|
+
}
|
|
2922
|
+
const GUIDANCE_SCHEMA = {
|
|
2923
|
+
type: "object",
|
|
2924
|
+
properties: {
|
|
2925
|
+
casting: strs("Each passage that says how to make people, places or things up while the story is played, copied exactly."),
|
|
2926
|
+
rules: strs("Each passage that is a standing rule or mechanic the game master applies as the story is played, copied exactly.")
|
|
2927
|
+
},
|
|
2928
|
+
required: ["casting", "rules"],
|
|
2929
|
+
additionalProperties: false
|
|
2930
|
+
};
|
|
2931
|
+
/** Pieces shorter than this hold no guidance worth a request of its own. */
|
|
2932
|
+
const MIN_GUIDANCE_CHARS = 120;
|
|
2933
|
+
/** The most characters of standing rules the game master carries on every turn; the rest of what the card always sends is found by search like any lore. */
|
|
2934
|
+
const STANDING_MAX_CHARS = 12e3;
|
|
2935
|
+
const STANDING_PROMPT = "roleplay/standing";
|
|
2936
|
+
const squeezed = (text) => text.replace(/\s+/g, " ").trim();
|
|
2937
|
+
/** Why the passages cannot be used, or nothing when each is in the piece word for word: the guidance is the card's, and a rewrite would be the model's. */
|
|
2938
|
+
function passageProblem(answer, source) {
|
|
2939
|
+
const whole = squeezed(source);
|
|
2940
|
+
for (const field of ["casting", "rules"]) {
|
|
2941
|
+
const missing = (Array.isArray(answer[field]) ? answer[field] : []).findIndex((passage) => typeof passage !== "string" || squeezed(passage) === "" || !whole.includes(squeezed(passage)));
|
|
2942
|
+
if (missing >= 0) return `${field} passage ${missing + 1} is not in the piece word for word: copy it exactly as written, or leave it out`;
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
/** The lore entry for the guidance found in a piece, in the card's own words, for the game master and the world author only. */
|
|
2946
|
+
function guidanceEntry(passages, title) {
|
|
2947
|
+
const body = passages.map((passage) => passage.trim()).join("\n\n");
|
|
2948
|
+
return {
|
|
2949
|
+
title: title.slice(0, 100),
|
|
2950
|
+
kind: "custom",
|
|
2951
|
+
scope: "listed",
|
|
2952
|
+
summary: (/^[^\n。.!?!?]*[。.!?!?]?/u.exec(body)?.[0] ?? body).slice(0, 200),
|
|
2953
|
+
body
|
|
2954
|
+
};
|
|
2955
|
+
}
|
|
2956
|
+
/** What a prompt file cannot hold is changed so that `${` and `{{` in a card's text are not read as variables. */
|
|
2957
|
+
const inert = (text) => text.replace(/\$\{/g, "$ {").replace(/\{\{/g, "{ {");
|
|
2958
|
+
const LORE_SCHEMA = {
|
|
2959
|
+
type: "object",
|
|
2960
|
+
properties: { entries: {
|
|
2961
|
+
type: "array",
|
|
2962
|
+
items: {
|
|
2963
|
+
type: "object",
|
|
2964
|
+
properties: {
|
|
2965
|
+
title: str("A short title."),
|
|
2966
|
+
kind: {
|
|
2967
|
+
type: "string",
|
|
2968
|
+
enum: [...LORE_KINDS]
|
|
2969
|
+
},
|
|
2970
|
+
summary: str("One sentence."),
|
|
2971
|
+
body: str("The facts, as prose."),
|
|
2972
|
+
subjects: {
|
|
2973
|
+
type: "array",
|
|
2974
|
+
items: {
|
|
2975
|
+
type: "object",
|
|
2976
|
+
properties: {
|
|
2977
|
+
kind: {
|
|
2978
|
+
type: "string",
|
|
2979
|
+
enum: [
|
|
2980
|
+
"character",
|
|
2981
|
+
"place",
|
|
2982
|
+
"faction",
|
|
2983
|
+
"thing"
|
|
2984
|
+
]
|
|
2985
|
+
},
|
|
2986
|
+
name: str("A name from the lists.")
|
|
2987
|
+
},
|
|
2988
|
+
required: ["kind", "name"],
|
|
2989
|
+
additionalProperties: false
|
|
2990
|
+
}
|
|
2991
|
+
}
|
|
2992
|
+
},
|
|
2993
|
+
required: [
|
|
2994
|
+
"title",
|
|
2995
|
+
"kind",
|
|
2996
|
+
"summary",
|
|
2997
|
+
"body"
|
|
2998
|
+
],
|
|
2999
|
+
additionalProperties: false
|
|
3000
|
+
}
|
|
3001
|
+
} },
|
|
3002
|
+
required: ["entries"],
|
|
3003
|
+
additionalProperties: false
|
|
3004
|
+
};
|
|
3005
|
+
const LORE_SUBJECT = {
|
|
3006
|
+
character: "character",
|
|
3007
|
+
place: "location",
|
|
3008
|
+
faction: "faction",
|
|
3009
|
+
thing: "item"
|
|
3010
|
+
};
|
|
3011
|
+
function loreDocuments(answer, roster, taken) {
|
|
3012
|
+
return objects(answer["entries"]).flatMap((entry) => {
|
|
3013
|
+
const title = text(entry["title"]);
|
|
3014
|
+
const body = text(entry["body"]);
|
|
3015
|
+
if (title === "" || body === "") return [];
|
|
3016
|
+
const notes = [];
|
|
3017
|
+
const subjects = [];
|
|
3018
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3019
|
+
for (const subject of objects(entry["subjects"])) {
|
|
3020
|
+
const kind = [
|
|
3021
|
+
"character",
|
|
3022
|
+
"place",
|
|
3023
|
+
"faction",
|
|
3024
|
+
"thing"
|
|
3025
|
+
].includes(text(subject["kind"])) ? text(subject["kind"]) : void 0;
|
|
3026
|
+
const found = kind === void 0 ? void 0 : findEntity(roster, text(subject["name"]), kind);
|
|
3027
|
+
if (found === void 0) {
|
|
3028
|
+
notes.push(`${title}: the subject "${text(subject["name"])}" is not in the world`);
|
|
3029
|
+
continue;
|
|
3030
|
+
}
|
|
3031
|
+
if (!seen.has(found.key)) {
|
|
3032
|
+
seen.add(found.key);
|
|
3033
|
+
subjects.push({
|
|
3034
|
+
kind: LORE_SUBJECT[found.kind],
|
|
3035
|
+
id: found.key
|
|
3036
|
+
});
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
const kind = LORE_KINDS.includes(entry["kind"]) ? entry["kind"] : "other";
|
|
3040
|
+
const document = {
|
|
3041
|
+
id: uniqueKey(slug(title, "lore"), taken),
|
|
3042
|
+
title,
|
|
3043
|
+
kind,
|
|
3044
|
+
summary: text(entry["summary"]),
|
|
3045
|
+
body
|
|
3046
|
+
};
|
|
3047
|
+
put(document, "subjects", subjects);
|
|
3048
|
+
return [{
|
|
3049
|
+
document,
|
|
3050
|
+
notes
|
|
3051
|
+
}];
|
|
3052
|
+
});
|
|
3053
|
+
}
|
|
3054
|
+
/** A background piece as one entry, in the card's own words: what is kept when the model cannot rewrite it without losing its facts. */
|
|
3055
|
+
function asWritten(item) {
|
|
3056
|
+
const body = item.text.trim();
|
|
3057
|
+
return { entries: [{
|
|
3058
|
+
title: (item.title === "" ? item.label : item.title).slice(0, 100),
|
|
3059
|
+
kind: "other",
|
|
3060
|
+
summary: (/^[^\n。.!?!?]*[。.!?!?]?/u.exec(body)?.[0] ?? body).slice(0, 200),
|
|
3061
|
+
body
|
|
3062
|
+
}] };
|
|
3063
|
+
}
|
|
3064
|
+
/** The entries of a piece must hold at least this share of its text, from a piece of at least `MIN_CHECKED_CHARS` characters: the facts are kept, not summarised away. */
|
|
3065
|
+
const MIN_LORE_SHARE = .5;
|
|
3066
|
+
const MIN_CHECKED_CHARS = 300;
|
|
3067
|
+
/** Why the entries made of a piece cannot be used, or nothing when they can. */
|
|
3068
|
+
function loreProblem(answer, roster, source) {
|
|
3069
|
+
const entries = loreDocuments(answer, roster, /* @__PURE__ */ new Set());
|
|
3070
|
+
if (entries.length === 0) return "write at least one entry with a title and a body";
|
|
3071
|
+
if (entries.length > 4) return `${entries.length} entries is too many for one piece: write at most 4, each with all the facts of its subject`;
|
|
3072
|
+
const kept = entries.reduce((total, entry) => total + String(entry.document["body"]).length, 0);
|
|
3073
|
+
const wanted = Math.round(source.length * MIN_LORE_SHARE);
|
|
3074
|
+
if (source.length >= MIN_CHECKED_CHARS && kept < wanted) return `the entries hold ${kept} characters of the ${source.length} of the piece: facts were left out. Keep every name, date, number, cause and rule; the bodies together need at least ${wanted} characters`;
|
|
3075
|
+
}
|
|
3076
|
+
/**
|
|
3077
|
+
* Characters the pieces that set the scene name, and that were given no starting place, start in the place those pieces are set in, when
|
|
3078
|
+
* there is exactly one: the story begins there, so whoever it opens with is there.
|
|
3079
|
+
*/
|
|
3080
|
+
function placeAtScenario(result, items, classified, roster) {
|
|
3081
|
+
const scenes = items.filter((item) => playsRole(classified[item.id] ?? { roles: [] }, "scenario"));
|
|
3082
|
+
const places = new Set(scenes.flatMap((item) => (classified[item.id]?.targets ?? []).filter((target) => target.kind === "place").flatMap((target) => {
|
|
3083
|
+
const found = findEntity(roster, target.name, "place");
|
|
3084
|
+
return found === void 0 ? [] : [found.key];
|
|
3085
|
+
})));
|
|
3086
|
+
if (places.size !== 1) return;
|
|
3087
|
+
const place = [...places][0];
|
|
3088
|
+
const present = new Set(scenes.flatMap((item) => (classified[item.id]?.targets ?? []).filter((target) => target.kind === "character").flatMap((target) => {
|
|
3089
|
+
const found = findEntity(roster, target.name, "character");
|
|
3090
|
+
return found === void 0 ? [] : [found.key];
|
|
3091
|
+
})));
|
|
3092
|
+
for (const character of result.characters) {
|
|
3093
|
+
if (!present.has(String(character["id"]))) continue;
|
|
3094
|
+
const start = character["start"] ?? {};
|
|
3095
|
+
if (start["location"] !== void 0) continue;
|
|
3096
|
+
character["start"] = {
|
|
3097
|
+
...start,
|
|
3098
|
+
location: place
|
|
3099
|
+
};
|
|
3100
|
+
}
|
|
3101
|
+
}
|
|
3102
|
+
/** Takes out of the lore the subjects that were not written (a thing that is nowhere and nobody's is not made), so that no entry names what the world does not have. */
|
|
3103
|
+
function pruneLoreSubjects(result) {
|
|
3104
|
+
const written = /* @__PURE__ */ new Set([
|
|
3105
|
+
...result.characters.map((entry) => `character:${String(entry["id"])}`),
|
|
3106
|
+
...result.locations.map((entry) => `location:${String(entry["id"])}`),
|
|
3107
|
+
...result.factions.map((entry) => `faction:${String(entry["id"])}`),
|
|
3108
|
+
...result.items.map((entry) => `item:${String(entry["id"])}`)
|
|
3109
|
+
]);
|
|
3110
|
+
for (const entry of result.lore) {
|
|
3111
|
+
const subjects = entry["subjects"] ?? [];
|
|
3112
|
+
const kept = subjects.filter((subject) => written.has(`${String(subject["kind"])}:${String(subject["id"])}`));
|
|
3113
|
+
if (kept.length === subjects.length) continue;
|
|
3114
|
+
result.notes.push(`${String(entry["title"])}: ${subjects.length - kept.length} subject(s) left out because the world has no such ${subjects.length - kept.length === 1 ? "entity" : "entities"}`);
|
|
3115
|
+
if (kept.length === 0) delete entry["subjects"];
|
|
3116
|
+
else entry["subjects"] = kept;
|
|
3117
|
+
}
|
|
3118
|
+
}
|
|
3119
|
+
/** Takes out of a faction the members whose character was not written (the job for it failed or it was left out): a faction that names no one is better than a world that cannot be written. */
|
|
3120
|
+
function pruneMembers(result) {
|
|
3121
|
+
const written = new Set(result.characters.map((entry) => String(entry["id"])));
|
|
3122
|
+
for (const faction of result.factions) {
|
|
3123
|
+
const members = objects(faction["members"]);
|
|
3124
|
+
const kept = members.filter((member) => written.has(String(member["character"])));
|
|
3125
|
+
if (kept.length === members.length) continue;
|
|
3126
|
+
result.notes.push(`${String(faction["name"])}: ${members.length - kept.length} member(s) left out because the world has no such character`);
|
|
3127
|
+
if (kept.length === 0) delete faction["members"];
|
|
3128
|
+
else faction["members"] = kept;
|
|
3129
|
+
}
|
|
3130
|
+
}
|
|
3131
|
+
/** Takes out of a place the parent and the ways that lead to a place that was not written, and out of a character a starting place that was not: each is only a link, and the document stays. */
|
|
3132
|
+
function pruneLinks(result) {
|
|
3133
|
+
const places = new Set(result.locations.map((entry) => String(entry["id"])));
|
|
3134
|
+
for (const place of result.locations) {
|
|
3135
|
+
if (place["parent"] !== void 0 && !places.has(String(place["parent"]))) {
|
|
3136
|
+
result.notes.push(`${String(place["name"])}: its parent place is left out because the world has no such place`);
|
|
3137
|
+
delete place["parent"];
|
|
3138
|
+
}
|
|
3139
|
+
const exits = objects(place["exits"]);
|
|
3140
|
+
const open = exits.filter((exit) => places.has(String(exit["to"])));
|
|
3141
|
+
if (open.length === exits.length) continue;
|
|
3142
|
+
result.notes.push(`${String(place["name"])}: ${exits.length - open.length} way(s) left out because they lead to a place the world does not have`);
|
|
3143
|
+
if (open.length === 0) delete place["exits"];
|
|
3144
|
+
else place["exits"] = open;
|
|
3145
|
+
}
|
|
3146
|
+
for (const character of result.characters) {
|
|
3147
|
+
const start = character["start"];
|
|
3148
|
+
if (start === void 0 || start["location"] === void 0 || places.has(String(start["location"]))) continue;
|
|
3149
|
+
result.notes.push(`${String(character["name"])}: its starting place is left out because the world has no such place`);
|
|
3150
|
+
delete start["location"];
|
|
3151
|
+
delete start["position"];
|
|
3152
|
+
delete start["feature"];
|
|
3153
|
+
if (Object.keys(start).length === 0) delete character["start"];
|
|
3154
|
+
}
|
|
3155
|
+
}
|
|
3156
|
+
/** Takes out of a character's relationships those with a character that was not written. */
|
|
3157
|
+
function pruneRelationships(result) {
|
|
3158
|
+
const written = new Set(result.characters.map((entry) => String(entry["id"])));
|
|
3159
|
+
for (const character of result.characters) {
|
|
3160
|
+
const relations = objects(character["relationships"]);
|
|
3161
|
+
const kept = relations.filter((relation) => written.has(String(relation["to"])));
|
|
3162
|
+
if (kept.length === relations.length) continue;
|
|
3163
|
+
result.notes.push(`${String(character["name"])}: ${relations.length - kept.length} relationship(s) left out because the world has no such character`);
|
|
3164
|
+
if (kept.length === 0) delete character["relationships"];
|
|
3165
|
+
else character["relationships"] = kept;
|
|
3166
|
+
}
|
|
3167
|
+
}
|
|
3168
|
+
/** Takes out of what characters know the places and things that were not written (a thing that is nowhere and nobody's is not made). */
|
|
3169
|
+
function pruneKnowledge(result) {
|
|
3170
|
+
const written = {
|
|
3171
|
+
locations: new Set(result.locations.map((entry) => String(entry["id"]))),
|
|
3172
|
+
items: new Set(result.items.map((entry) => String(entry["id"])))
|
|
3173
|
+
};
|
|
3174
|
+
const ways = new Set(result.locations.flatMap((place) => objects(place["exits"]).map((exit) => `${String(place["id"])}>${String(exit["to"])}`)));
|
|
3175
|
+
for (const character of result.characters) {
|
|
3176
|
+
const knowledge = character["knowledge"];
|
|
3177
|
+
if (knowledge === void 0) continue;
|
|
3178
|
+
const routes = objects(knowledge["exits"]);
|
|
3179
|
+
const open = routes.filter((route) => ways.has(`${String(route["from"])}>${String(route["to"])}`));
|
|
3180
|
+
if (open.length !== routes.length) {
|
|
3181
|
+
result.notes.push(`${String(character["name"])}: ${routes.length - open.length} known way(s) left out because the world has no such way`);
|
|
3182
|
+
if (open.length === 0) delete knowledge["exits"];
|
|
3183
|
+
else knowledge["exits"] = open;
|
|
3184
|
+
}
|
|
3185
|
+
for (const field of ["locations", "items"]) {
|
|
3186
|
+
const keys = knowledge[field] ?? [];
|
|
3187
|
+
const kept = keys.filter((key) => written[field].has(key));
|
|
3188
|
+
if (kept.length === keys.length) continue;
|
|
3189
|
+
result.notes.push(`${String(character["name"])}: ${keys.length - kept.length} known ${field === "items" ? "thing(s)" : "place(s)"} left out because the world has no such entity`);
|
|
3190
|
+
if (kept.length === 0) delete knowledge[field];
|
|
3191
|
+
else knowledge[field] = kept;
|
|
3192
|
+
}
|
|
3193
|
+
if (Object.keys(knowledge).length === 0) delete character["knowledge"];
|
|
3194
|
+
}
|
|
3195
|
+
}
|
|
3196
|
+
/**
|
|
3197
|
+
* Completes what characters are aware of, because a missing edge means a character does not know the other exists: a character named in someone's relationships
|
|
3198
|
+
* knows of that someone (a neutral acquaintance, added when the character has none), and knows the lore that is about them.
|
|
3199
|
+
*/
|
|
3200
|
+
function completeAwareness(result) {
|
|
3201
|
+
const byId = new Map(result.characters.map((character) => [String(character["id"]), character]));
|
|
3202
|
+
let added = 0;
|
|
3203
|
+
for (const character of result.characters) for (const relation of character["relationships"] ?? []) {
|
|
3204
|
+
const other = byId.get(String(relation["to"]));
|
|
3205
|
+
if (other === void 0 || other === character) continue;
|
|
3206
|
+
const theirs = other["relationships"] ?? [];
|
|
3207
|
+
if (theirs.some((entry) => entry["to"] === character["id"])) continue;
|
|
3208
|
+
other["relationships"] = [...theirs, {
|
|
3209
|
+
to: character["id"],
|
|
3210
|
+
label: "acquaintance"
|
|
3211
|
+
}];
|
|
3212
|
+
added += 1;
|
|
3213
|
+
}
|
|
3214
|
+
if (added > 0) result.notes.push(`${added} relationship(s) were added in the other direction as plain acquaintances, so that both characters know of each other`);
|
|
3215
|
+
for (const entry of result.lore) for (const subject of entry["subjects"] ?? []) {
|
|
3216
|
+
const character = subject["kind"] === "character" ? byId.get(String(subject["id"])) : void 0;
|
|
3217
|
+
if (character === void 0) continue;
|
|
3218
|
+
const knowledge = character["knowledge"] ?? (character["knowledge"] = {});
|
|
3219
|
+
const known = knowledge["lore"] ?? [];
|
|
3220
|
+
if (!known.includes(String(entry["id"]))) knowledge["lore"] = [...known, String(entry["id"])];
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
/** Adds an entry unless the world already has it: the same title, or a body that an earlier entry already contains (a longer one replaces a shorter that it contains). */
|
|
3224
|
+
function addLore(lore, entry) {
|
|
3225
|
+
const title = norm(String(entry["title"]));
|
|
3226
|
+
const body = norm(String(entry["body"]));
|
|
3227
|
+
const same = lore.findIndex((other) => {
|
|
3228
|
+
const otherBody = norm(String(other["body"]));
|
|
3229
|
+
return norm(String(other["title"])) === title || otherBody.includes(body) || body.includes(otherBody);
|
|
3230
|
+
});
|
|
3231
|
+
if (same < 0) {
|
|
3232
|
+
lore.push(entry);
|
|
3233
|
+
return;
|
|
3234
|
+
}
|
|
3235
|
+
if (body.length > norm(String(lore[same]["body"])).length) lore[same] = {
|
|
3236
|
+
...entry,
|
|
3237
|
+
id: lore[same]["id"]
|
|
3238
|
+
};
|
|
3239
|
+
}
|
|
3240
|
+
/** The file a document will be, read as the world will read it: why it cannot be, if it cannot. */
|
|
3241
|
+
function documentProblem(kind, document) {
|
|
3242
|
+
const parse = {
|
|
3243
|
+
character: parseCharacterFile,
|
|
3244
|
+
location: parseLocationFile,
|
|
3245
|
+
faction: parseFactionFile,
|
|
3246
|
+
item: parseItemFile,
|
|
3247
|
+
lore: parseLoreFile
|
|
3248
|
+
}[kind];
|
|
3249
|
+
const parsed = parse(JSON.stringify(document), String(document["id"]));
|
|
3250
|
+
return parsed.ok ? void 0 : parsed.issues.map(formatIssue).join("; ");
|
|
3251
|
+
}
|
|
3252
|
+
const GROUP_KINDS = {
|
|
3253
|
+
character: "character",
|
|
3254
|
+
place: "location",
|
|
3255
|
+
faction: "faction",
|
|
3256
|
+
thing: "item"
|
|
3257
|
+
};
|
|
3258
|
+
function jobFor(text, tr, entity, sources, roster, card) {
|
|
3259
|
+
const prompt = promptFor(entity, sources, roster, card, tr);
|
|
3260
|
+
const make = {
|
|
3261
|
+
character: characterDocument,
|
|
3262
|
+
place: placeDocument,
|
|
3263
|
+
faction: factionDocument,
|
|
3264
|
+
thing: thingDocument
|
|
3265
|
+
}[entity.kind];
|
|
3266
|
+
return {
|
|
3267
|
+
persona: text(`import/${entity.kind}`, { rules: text("import/common-rules") }),
|
|
3268
|
+
maxTokens: entity.kind === "character" ? 6e3 : 3e3,
|
|
3269
|
+
prompt,
|
|
3270
|
+
result: {
|
|
3271
|
+
character: CHARACTER_SCHEMA,
|
|
3272
|
+
place: PLACE_SCHEMA,
|
|
3273
|
+
faction: FACTION_SCHEMA,
|
|
3274
|
+
thing: THING_SCHEMA
|
|
3275
|
+
}[entity.kind],
|
|
3276
|
+
check: (answer) => {
|
|
3277
|
+
const { document } = make(entity, answer, roster);
|
|
3278
|
+
if (entity.kind === "thing" && document["held_by"] === void 0 && document["location"] === void 0) return void 0;
|
|
3279
|
+
return documentProblem(GROUP_KINDS[entity.kind], document);
|
|
3280
|
+
}
|
|
3281
|
+
};
|
|
3282
|
+
}
|
|
3283
|
+
/** Makes the documents of every entity of the roster, and the lore from the pieces about the world. */
|
|
3284
|
+
async function extractEntities(ctx, card, items, classified, roster) {
|
|
3285
|
+
const result = emptyExtracted();
|
|
3286
|
+
const entityResults = await mapLimit(roster, ctx.concurrency, async (entity, index) => {
|
|
3287
|
+
ctx.say(`writing ${entity.kind} ${index + 1}/${roster.length}: ${entity.name}`);
|
|
3288
|
+
const sources = sourcesFor(entity, items, classified);
|
|
3289
|
+
try {
|
|
3290
|
+
const answer = await ctx.run(jobFor(ctx.text, trOf(ctx), entity, sources, roster, card));
|
|
3291
|
+
return {
|
|
3292
|
+
entity,
|
|
3293
|
+
built: {
|
|
3294
|
+
character: characterDocument,
|
|
3295
|
+
place: placeDocument,
|
|
3296
|
+
faction: factionDocument,
|
|
3297
|
+
thing: thingDocument
|
|
3298
|
+
}[entity.kind](entity, answer, roster)
|
|
3299
|
+
};
|
|
3300
|
+
} catch (error) {
|
|
3301
|
+
return {
|
|
3302
|
+
entity,
|
|
3303
|
+
failure: `${entity.kind} ${entity.name}: ${error instanceof Error ? error.message : String(error)}`
|
|
3304
|
+
};
|
|
3305
|
+
}
|
|
3306
|
+
});
|
|
3307
|
+
for (const { entity, built, failure } of entityResults) {
|
|
3308
|
+
if (failure !== void 0 || built === void 0) {
|
|
3309
|
+
result.notes.push(failure ?? `${entity.name}: nothing was written`);
|
|
3310
|
+
continue;
|
|
3311
|
+
}
|
|
3312
|
+
result.notes.push(...built.notes);
|
|
3313
|
+
if (entity.kind === "thing" && built.document["held_by"] === void 0 && built.document["location"] === void 0) continue;
|
|
3314
|
+
result[{
|
|
3315
|
+
character: "characters",
|
|
3316
|
+
place: "locations",
|
|
3317
|
+
faction: "factions",
|
|
3318
|
+
thing: "items"
|
|
3319
|
+
}[entity.kind]].push(built.document);
|
|
3320
|
+
}
|
|
3321
|
+
const worldItems = items.filter((item) => statesWorldFacts(classified[item.id] ?? { roles: [] }));
|
|
3322
|
+
const taken = /* @__PURE__ */ new Set();
|
|
3323
|
+
const loreResults = await mapLimit(worldItems, ctx.concurrency, async (item, index) => {
|
|
3324
|
+
ctx.say(`writing background ${index + 1}/${worldItems.length}: ${item.label}`);
|
|
3325
|
+
try {
|
|
3326
|
+
const tr = trOf(ctx);
|
|
3327
|
+
const prompt = `${tr("Card: {name}", { name: card.name })}\n${tr("Piece: {label}", { label: item.label })}${item.title === "" ? "" : `\n${tr("Title: {title}", { title: item.title })}`}\n\n${tr("The entities of this world, which are the only ones the entries may name as subjects:")}\n${rosterLines(roster, tr)}\n\n${tr("Source piece:")}\n${item.text.slice(0, 5500)}`;
|
|
3328
|
+
return {
|
|
3329
|
+
item,
|
|
3330
|
+
answer: await ctx.run({
|
|
3331
|
+
persona: ctx.text("import/lore", { rules: ctx.text("import/common-rules") }),
|
|
3332
|
+
maxTokens: 1500 + item.text.length,
|
|
3333
|
+
prompt,
|
|
3334
|
+
result: LORE_SCHEMA,
|
|
3335
|
+
check: (value) => loreProblem(value, roster, item.text)
|
|
3336
|
+
})
|
|
3337
|
+
};
|
|
3338
|
+
} catch (error) {
|
|
3339
|
+
return {
|
|
3340
|
+
item,
|
|
3341
|
+
answer: asWritten(item),
|
|
3342
|
+
failure: `${item.label}: kept as the card wrote it, because the model could not rewrite it (${error instanceof Error ? error.message : String(error)})`
|
|
3343
|
+
};
|
|
3344
|
+
}
|
|
3345
|
+
});
|
|
3346
|
+
for (const { answer, failure } of loreResults) {
|
|
3347
|
+
if (failure !== void 0) result.notes.push(failure);
|
|
3348
|
+
if (answer === void 0) {
|
|
3349
|
+
result.notes.push("a background piece produced nothing");
|
|
3350
|
+
continue;
|
|
3351
|
+
}
|
|
3352
|
+
for (const built of loreDocuments(answer, roster, taken)) {
|
|
3353
|
+
result.notes.push(...built.notes);
|
|
3354
|
+
addLore(result.lore, built.document);
|
|
3355
|
+
}
|
|
3356
|
+
}
|
|
3357
|
+
for (const item of items.filter((item) => playsRole(classified[item.id] ?? { roles: [] }, "generator"))) for (const built of loreDocuments(asWritten(item), roster, taken)) addLore(result.lore, {
|
|
3358
|
+
...built.document,
|
|
3359
|
+
kind: "custom",
|
|
3360
|
+
scope: "listed"
|
|
3361
|
+
});
|
|
3362
|
+
const tr = trOf(ctx);
|
|
3363
|
+
const searched = items.filter((item) => item.text.length >= MIN_GUIDANCE_CHARS && mayHoldGuidance(classified[item.id] ?? { roles: ["world"] }));
|
|
3364
|
+
const found = await mapLimit(searched, ctx.concurrency, async (item, index) => {
|
|
3365
|
+
ctx.say(`looking for guidance on making things up and for standing rules ${index + 1}/${searched.length}: ${item.label}`);
|
|
3366
|
+
try {
|
|
3367
|
+
const prompt = `${tr("Card: {name}", { name: card.name })}\n${tr("Piece: {label}", { label: item.label })}\n\n${tr("Source piece:")}\n${item.text.slice(0, 5500)}`;
|
|
3368
|
+
const answer = await ctx.run({
|
|
3369
|
+
persona: ctx.text("import/generator", { rules: ctx.text("import/common-rules") }),
|
|
3370
|
+
maxTokens: 600 + item.text.length,
|
|
3371
|
+
prompt,
|
|
3372
|
+
result: GUIDANCE_SCHEMA,
|
|
3373
|
+
check: (value) => passageProblem(value, item.text)
|
|
3374
|
+
});
|
|
3375
|
+
const passages = (field) => answer[field].filter((passage) => passage.trim() !== "");
|
|
3376
|
+
return {
|
|
3377
|
+
item,
|
|
3378
|
+
casting: passages("casting"),
|
|
3379
|
+
rules: passages("rules")
|
|
3380
|
+
};
|
|
3381
|
+
} catch (error) {
|
|
3382
|
+
return {
|
|
3383
|
+
item,
|
|
3384
|
+
casting: [],
|
|
3385
|
+
rules: [],
|
|
3386
|
+
failure: `${item.label}: ${error instanceof Error ? error.message : String(error)}`
|
|
3387
|
+
};
|
|
3388
|
+
}
|
|
3389
|
+
});
|
|
3390
|
+
let standing = "";
|
|
3391
|
+
for (const { item, casting, rules, failure } of found) {
|
|
3392
|
+
if (failure !== void 0) result.notes.push(failure);
|
|
3393
|
+
const name = item.title === "" ? item.label : item.title;
|
|
3394
|
+
result.casting.push(...casting);
|
|
3395
|
+
if (casting.length > 0) addLore(result.lore, {
|
|
3396
|
+
id: uniqueKey(slug(item.label, "guidance"), taken),
|
|
3397
|
+
...guidanceEntry(casting, tr("{label}: how people are made up", { label: name }))
|
|
3398
|
+
});
|
|
3399
|
+
if (rules.length === 0) continue;
|
|
3400
|
+
const block = `## ${name}\n${rules.map((passage) => passage.trim()).join("\n\n")}`;
|
|
3401
|
+
if (item.constant === true && standing.length + block.length <= STANDING_MAX_CHARS) standing += `${standing === "" ? "" : "\n\n"}${block}`;
|
|
3402
|
+
else addLore(result.lore, {
|
|
3403
|
+
id: uniqueKey(slug(item.label, "rules"), taken),
|
|
3404
|
+
...guidanceEntry(rules, tr("{label}: rules and mechanics", { label: name }))
|
|
3405
|
+
});
|
|
3406
|
+
}
|
|
3407
|
+
if (standing !== "") result.prompts.push({
|
|
3408
|
+
id: STANDING_PROMPT,
|
|
3409
|
+
text: inert(standing)
|
|
3410
|
+
});
|
|
3411
|
+
placeAtScenario(result, items, classified, roster);
|
|
3412
|
+
pruneLoreSubjects(result);
|
|
3413
|
+
pruneMembers(result);
|
|
3414
|
+
pruneLinks(result);
|
|
3415
|
+
pruneKnowledge(result);
|
|
3416
|
+
completeAwareness(result);
|
|
3417
|
+
return result;
|
|
3418
|
+
}
|
|
3419
|
+
const STYLE_SCHEMA = {
|
|
3420
|
+
type: "object",
|
|
3421
|
+
properties: {
|
|
3422
|
+
narration: {
|
|
3423
|
+
type: "string",
|
|
3424
|
+
description: "How the narration is written: voice, tone, perspective, pacing, level of detail. Empty when the instructions say nothing about it."
|
|
3425
|
+
},
|
|
3426
|
+
characters: {
|
|
3427
|
+
type: "string",
|
|
3428
|
+
description: "How every character speaks and behaves: staying in character, manner, and how it deals with what it is asked to do or refuses. Use ${name} for the character. Empty when the instructions say nothing about it."
|
|
3429
|
+
},
|
|
3430
|
+
left_out: {
|
|
3431
|
+
type: "array",
|
|
3432
|
+
items: { type: "string" },
|
|
3433
|
+
description: "What the instructions contained that is not prose or behaviour guidance (rules of the game, formats, panels, scripts), one short phrase each."
|
|
3434
|
+
},
|
|
3435
|
+
persona_names: {
|
|
3436
|
+
type: "array",
|
|
3437
|
+
items: { type: "string" },
|
|
3438
|
+
description: "Every name the instructions give to the AI itself (a writer, narrator or assistant persona), exactly as written; empty when it has none. These names must not appear in narration or characters."
|
|
3439
|
+
}
|
|
3440
|
+
},
|
|
3441
|
+
required: [
|
|
3442
|
+
"narration",
|
|
3443
|
+
"characters",
|
|
3444
|
+
"left_out",
|
|
3445
|
+
"persona_names"
|
|
3446
|
+
]
|
|
3447
|
+
};
|
|
3448
|
+
const MAX_STYLE_CHARS = 2e3;
|
|
3449
|
+
/** The instructions to the AI that a card carries: its own system and post-history fields, and the pieces judged to be instructions. */
|
|
3450
|
+
function instructionPieces(card, items, classified) {
|
|
3451
|
+
const fields = [card.systemPrompt, card.postHistoryInstructions].map((field) => cleanText(field, card.name)).filter((field) => field !== "");
|
|
3452
|
+
const pieces = items.filter((item) => mainRole(classified[item.id] ?? { roles: [] }) === "instruction").map((item) => item.text);
|
|
3453
|
+
return [...fields, ...pieces];
|
|
3454
|
+
}
|
|
3455
|
+
function styleProblem(id, value, personas = []) {
|
|
3456
|
+
const named = personas.find((name) => name.trim() !== "" && value.toLowerCase().includes(name.trim().toLowerCase()));
|
|
3457
|
+
if (named !== void 0) return `${id} uses the persona name "${named}"; say "the character" or "the narrator" instead`;
|
|
3458
|
+
if (value.length > MAX_STYLE_CHARS) return `${id} is ${value.length} characters long; keep it to ${MAX_STYLE_CHARS}`;
|
|
3459
|
+
return value === "" ? void 0 : promptProblem("en", id, value);
|
|
3460
|
+
}
|
|
3461
|
+
/** Turns the instructions of a card into the prose prompts of the world. Only prose and behaviour are kept: the rules of the game stay the program's. */
|
|
3462
|
+
async function extractStyle(ctx, card, items, classified) {
|
|
3463
|
+
return await extractStyleFrom(ctx, card.name, instructionPieces(card, items, classified));
|
|
3464
|
+
}
|
|
3465
|
+
/** The prose prompts that instruction texts become, and what was left out of them. */
|
|
3466
|
+
async function extractStyleFrom(ctx, name, pieces) {
|
|
3467
|
+
if (pieces.length === 0) return {
|
|
3468
|
+
prompts: [],
|
|
3469
|
+
notes: []
|
|
3470
|
+
};
|
|
3471
|
+
ctx.say("writing the style prompts");
|
|
3472
|
+
try {
|
|
3473
|
+
const tr = trOf(ctx);
|
|
3474
|
+
const prompt = `${tr("Card: {name}", { name })}\n\n${tr("The instructions of the card:")}\n\n${pieces.join("\n\n---\n\n").slice(0, SOURCE_BUDGET_CHARS)}`;
|
|
3475
|
+
const answer = await ctx.run({
|
|
3476
|
+
persona: ctx.text("import/style", { rules: ctx.text("import/common-rules") }),
|
|
3477
|
+
maxTokens: 8e3,
|
|
3478
|
+
prompt,
|
|
3479
|
+
result: STYLE_SCHEMA,
|
|
3480
|
+
check: (value) => styleProblem("roleplay/style", text(value.narration), list(value.persona_names)) ?? styleProblem("roleplay/character-style", text(value.characters), list(value.persona_names))
|
|
3481
|
+
});
|
|
3482
|
+
const prompts = [["roleplay/style", text(answer.narration)], ["roleplay/character-style", text(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
|
|
3483
|
+
id,
|
|
3484
|
+
text: body
|
|
3485
|
+
}]);
|
|
3486
|
+
if (!prompts.every((entry) => PROSE_PROMPTS.includes(entry.id))) throw new Error("only prose prompts can be made");
|
|
3487
|
+
return {
|
|
3488
|
+
prompts,
|
|
3489
|
+
notes: list(answer.left_out).map((entry) => `instructions not carried: ${entry}`)
|
|
3490
|
+
};
|
|
3491
|
+
} catch (error) {
|
|
3492
|
+
return {
|
|
3493
|
+
prompts: [],
|
|
3494
|
+
notes: [`the instructions of the card were not carried over: ${error instanceof Error ? error.message : String(error)}`]
|
|
3495
|
+
};
|
|
3496
|
+
}
|
|
3497
|
+
}
|
|
3498
|
+
const VARIABLES_SCHEMA = {
|
|
3499
|
+
type: "object",
|
|
3500
|
+
properties: {
|
|
3501
|
+
variables: {
|
|
3502
|
+
type: "array",
|
|
3503
|
+
items: {
|
|
3504
|
+
type: "object",
|
|
3505
|
+
properties: {
|
|
3506
|
+
key: {
|
|
3507
|
+
type: "string",
|
|
3508
|
+
description: "Lowercase ASCII letters, digits and underscores, starting with a letter: trust_meter."
|
|
3509
|
+
},
|
|
3510
|
+
name: { type: "string" },
|
|
3511
|
+
description: {
|
|
3512
|
+
type: "string",
|
|
3513
|
+
description: "What it measures, in a sentence."
|
|
3514
|
+
},
|
|
3515
|
+
kind: {
|
|
3516
|
+
type: "string",
|
|
3517
|
+
enum: [
|
|
3518
|
+
"number",
|
|
3519
|
+
"flag",
|
|
3520
|
+
"choice"
|
|
3521
|
+
]
|
|
3522
|
+
},
|
|
3523
|
+
subject: {
|
|
3524
|
+
type: "string",
|
|
3525
|
+
enum: [
|
|
3526
|
+
"character",
|
|
3527
|
+
"item",
|
|
3528
|
+
"location",
|
|
3529
|
+
"world"
|
|
3530
|
+
]
|
|
3531
|
+
},
|
|
3532
|
+
visibility: {
|
|
3533
|
+
type: "string",
|
|
3534
|
+
enum: [
|
|
3535
|
+
"public",
|
|
3536
|
+
"private",
|
|
3537
|
+
"hidden"
|
|
3538
|
+
]
|
|
3539
|
+
},
|
|
3540
|
+
only: {
|
|
3541
|
+
type: "array",
|
|
3542
|
+
items: { type: "string" },
|
|
3543
|
+
description: "Names from the lists of characters, places or things it is limited to; empty for all."
|
|
3544
|
+
},
|
|
3545
|
+
min: {
|
|
3546
|
+
oneOf: [{ type: "number" }, { type: "null" }],
|
|
3547
|
+
description: "The lowest value the card allows, or null."
|
|
3548
|
+
},
|
|
3549
|
+
max: {
|
|
3550
|
+
oneOf: [{ type: "number" }, { type: "null" }],
|
|
3551
|
+
description: "The highest value the card allows, or null."
|
|
3552
|
+
},
|
|
3553
|
+
integer: {
|
|
3554
|
+
type: "boolean",
|
|
3555
|
+
description: "True when it counts whole units."
|
|
3556
|
+
},
|
|
3557
|
+
default: {
|
|
3558
|
+
oneOf: [
|
|
3559
|
+
{ type: "number" },
|
|
3560
|
+
{ type: "boolean" },
|
|
3561
|
+
{ type: "string" },
|
|
3562
|
+
{ type: "null" }
|
|
3563
|
+
],
|
|
3564
|
+
description: "Where it starts: a number, true or false, or one of the options; null when the card does not say."
|
|
3565
|
+
},
|
|
3566
|
+
options: {
|
|
3567
|
+
type: "array",
|
|
3568
|
+
items: { type: "string" }
|
|
3569
|
+
},
|
|
3570
|
+
bands: {
|
|
3571
|
+
type: "array",
|
|
3572
|
+
items: {
|
|
3573
|
+
type: "object",
|
|
3574
|
+
properties: {
|
|
3575
|
+
up_to: { type: "number" },
|
|
3576
|
+
label: { type: "string" }
|
|
3577
|
+
},
|
|
3578
|
+
required: ["up_to", "label"],
|
|
3579
|
+
additionalProperties: false
|
|
3580
|
+
}
|
|
3581
|
+
}
|
|
3582
|
+
},
|
|
3583
|
+
required: [
|
|
3584
|
+
"key",
|
|
3585
|
+
"name",
|
|
3586
|
+
"description",
|
|
3587
|
+
"kind",
|
|
3588
|
+
"subject",
|
|
3589
|
+
"visibility",
|
|
3590
|
+
"only",
|
|
3591
|
+
"min",
|
|
3592
|
+
"max",
|
|
3593
|
+
"integer",
|
|
3594
|
+
"default",
|
|
3595
|
+
"options",
|
|
3596
|
+
"bands"
|
|
3597
|
+
],
|
|
3598
|
+
additionalProperties: false
|
|
3599
|
+
}
|
|
3600
|
+
},
|
|
3601
|
+
left_out: {
|
|
3602
|
+
type: "array",
|
|
3603
|
+
items: { type: "string" },
|
|
3604
|
+
description: "What the card contained that is not a tracked value, one short phrase each."
|
|
3605
|
+
}
|
|
3606
|
+
},
|
|
3607
|
+
required: ["variables", "left_out"]
|
|
3608
|
+
};
|
|
3609
|
+
/** The pieces that may describe what a card tracks: its panels and formats, and its instructions. */
|
|
3610
|
+
/** What a card that keeps its game state in variables says of them: the tool that updates them names itself in the text, whatever role the piece was given. */
|
|
3611
|
+
const STATE_SPEC = /stat_data|\[mvu_|<UpdateVariable>|<initvar>|JSON ?Patch/i;
|
|
3612
|
+
function trackingPieces(card, items, classified) {
|
|
3613
|
+
const specs = items.filter((item) => mainRole(classified[item.id] ?? { roles: [] }) !== "irrelevant" && STATE_SPEC.test(item.text)).map((item) => item.text);
|
|
3614
|
+
return [.../* @__PURE__ */ new Set([
|
|
3615
|
+
...items.filter((item) => mainRole(classified[item.id] ?? { roles: [] }) === "template").map((item) => item.text),
|
|
3616
|
+
...instructionPieces(card, items, classified),
|
|
3617
|
+
...specs
|
|
3618
|
+
])];
|
|
3619
|
+
}
|
|
3620
|
+
/** The documents of `variables.json` an answer describes, with the roster's names turned into keys. */
|
|
3621
|
+
function variableDocuments(answer, roster) {
|
|
3622
|
+
const keyOf = (name) => roster.find((entity) => norm(entity.name) === norm(name) || entity.aliases.some((alias) => norm(alias) === norm(name)))?.key;
|
|
3623
|
+
const taken = /* @__PURE__ */ new Set();
|
|
3624
|
+
return objects(answer["variables"]).map((entry, index) => {
|
|
3625
|
+
const base = slug(text(entry["key"]) || text(entry["name"]), "").replace(/-/g, "_").slice(0, 40);
|
|
3626
|
+
const document = {
|
|
3627
|
+
key: uniqueKey(/^[a-z][a-z0-9_]*$/.test(base) ? base : `variable_${index + 1}`, taken),
|
|
3628
|
+
name: text(entry["name"]),
|
|
3629
|
+
kind: text(entry["kind"]),
|
|
3630
|
+
subject: text(entry["subject"])
|
|
3631
|
+
};
|
|
3632
|
+
put(document, "description", text(entry["description"]));
|
|
3633
|
+
put(document, "visibility", text(entry["visibility"]));
|
|
3634
|
+
put(document, "only", list(entry["only"]).flatMap((name) => keyOf(name) ?? []));
|
|
3635
|
+
for (const field of ["min", "max"]) if (typeof entry[field] === "number") document[field] = entry[field];
|
|
3636
|
+
if (typeof entry["integer"] === "boolean") document["integer"] = entry["integer"];
|
|
3637
|
+
if ([
|
|
3638
|
+
"number",
|
|
3639
|
+
"boolean",
|
|
3640
|
+
"string"
|
|
3641
|
+
].includes(typeof entry["default"])) document["default"] = entry["default"];
|
|
3642
|
+
put(document, "options", list(entry["options"]));
|
|
3643
|
+
put(document, "bands", objects(entry["bands"]).filter((band) => typeof band["up_to"] === "number" && text(band["label"]) !== "").map((band) => ({
|
|
3644
|
+
up_to: band["up_to"],
|
|
3645
|
+
label: text(band["label"])
|
|
3646
|
+
})));
|
|
3647
|
+
return document;
|
|
3648
|
+
});
|
|
3649
|
+
}
|
|
3650
|
+
/** What is wrong with the declarations, as the world would find it; nothing when they can be used. */
|
|
3651
|
+
function variablesProblem(documents, roster) {
|
|
3652
|
+
const parsed = parseVariablesFile(JSON.stringify(documents));
|
|
3653
|
+
if (!parsed.ok) return parsed.issues.map((issue) => `${issue.path} ${issue.message}`.trim()).join("; ");
|
|
3654
|
+
const ids = (kind) => roster.filter((entity) => entity.kind === kind).map((entity) => ({ id: entity.key }));
|
|
3655
|
+
const problems = variableProblems({
|
|
3656
|
+
defs: parsed.value,
|
|
3657
|
+
characters: ids("character"),
|
|
3658
|
+
items: ids("thing"),
|
|
3659
|
+
locations: ids("place"),
|
|
3660
|
+
values: void 0
|
|
3661
|
+
});
|
|
3662
|
+
return problems.length === 0 ? void 0 : problems.join("; ");
|
|
3663
|
+
}
|
|
3664
|
+
/** The most of the card's tracking text one request reads: a request with all of it made the model write on until its limit without answering. */
|
|
3665
|
+
const TRACKING_GROUP_CHARS = 6e3;
|
|
3666
|
+
/** The pieces cut into groups that each fit one request, in order. */
|
|
3667
|
+
function trackingGroups(pieces, max = TRACKING_GROUP_CHARS) {
|
|
3668
|
+
const groups = [];
|
|
3669
|
+
let size = 0;
|
|
3670
|
+
for (const piece of pieces) {
|
|
3671
|
+
const text = piece.length > max ? piece.slice(0, max) : piece;
|
|
3672
|
+
if (groups.length === 0 || size + text.length > max) {
|
|
3673
|
+
groups.push([]);
|
|
3674
|
+
size = 0;
|
|
3675
|
+
}
|
|
3676
|
+
groups.at(-1).push(text);
|
|
3677
|
+
size += text.length;
|
|
3678
|
+
}
|
|
3679
|
+
return groups;
|
|
3680
|
+
}
|
|
3681
|
+
/** How many tracked values one request is asked to declare when nothing says otherwise, and how many requests one group of the card's text may take: a card that tracks more is asked again for the rest. */
|
|
3682
|
+
const DEFAULT_VARIABLES_PER_REQUEST = 25;
|
|
3683
|
+
const MAX_VARIABLE_ROUNDS = 12;
|
|
3684
|
+
const TOKENS_PER_VARIABLE = 600;
|
|
3685
|
+
/** Finds what the card keeps track of, such as status panels and meters, and writes it as the world's tracked variables. Each group of the card's tracking text is read on its own, a request declares at most `variablesPerRequest` values and is asked again, told what is declared already, while it fills its share; the first declaration of a key stands. */
|
|
3686
|
+
async function extractVariables(ctx, card, items, classified, roster) {
|
|
3687
|
+
const groups = trackingGroups(trackingPieces(card, items, classified));
|
|
3688
|
+
if (groups.length === 0) return {
|
|
3689
|
+
variables: [],
|
|
3690
|
+
notes: []
|
|
3691
|
+
};
|
|
3692
|
+
const perRequest = ctx.variablesPerRequest ?? DEFAULT_VARIABLES_PER_REQUEST;
|
|
3693
|
+
const names = (kind) => roster.filter((entity) => entity.kind === kind).map((entity) => entity.name).join(", ");
|
|
3694
|
+
const tr = trOf(ctx);
|
|
3695
|
+
const found = await mapLimit(groups, ctx.concurrency, async (pieces, index) => {
|
|
3696
|
+
const documents = [];
|
|
3697
|
+
const notes = [];
|
|
3698
|
+
for (let round = 1; round <= MAX_VARIABLE_ROUNDS; round += 1) {
|
|
3699
|
+
ctx.say(`looking for what the card tracks ${index + 1}/${groups.length}${round === 1 ? "" : `, round ${round}`}`);
|
|
3700
|
+
try {
|
|
3701
|
+
const declared = documents.length === 0 ? "" : `\n\n${tr("Already declared (do not declare them again):")} ${documents.map((document) => text(document["key"])).join(", ")}`;
|
|
3702
|
+
const prompt = `${tr("Card: {name}", { name: card.name })}\n\n${tr("Characters:")} ${names("character")}\n${tr("Places:")} ${names("place")}\n${tr("Things:")} ${names("thing")}\n\n${tr("The pieces of the card that may describe what it tracks:")}\n\n${pieces.join("\n\n---\n\n")}${declared}`;
|
|
3703
|
+
const answer = await ctx.run({
|
|
3704
|
+
persona: ctx.text("import/variables", {
|
|
3705
|
+
rules: ctx.text("import/common-rules"),
|
|
3706
|
+
max: perRequest
|
|
3707
|
+
}),
|
|
3708
|
+
maxTokens: Math.max(6e3, perRequest * TOKENS_PER_VARIABLE),
|
|
3709
|
+
prompt,
|
|
3710
|
+
result: VARIABLES_SCHEMA
|
|
3711
|
+
});
|
|
3712
|
+
const proposed = [];
|
|
3713
|
+
for (const document of variableDocuments(answer, roster)) {
|
|
3714
|
+
const problem = variablesProblem([document], roster);
|
|
3715
|
+
if (problem === void 0) proposed.push(document);
|
|
3716
|
+
else notes.push(`not tracked: ${text(document["name"])}: ${problem}`);
|
|
3717
|
+
}
|
|
3718
|
+
const fresh = proposed.filter((document) => !documents.some((kept) => kept["key"] === document["key"]));
|
|
3719
|
+
documents.push(...fresh);
|
|
3720
|
+
if (round === 1) notes.push(...list(answer["left_out"]).map((entry) => `not tracked: ${entry}`));
|
|
3721
|
+
if (proposed.length < perRequest || fresh.length === 0) break;
|
|
3722
|
+
} catch (error) {
|
|
3723
|
+
notes.push(`what part ${index + 1} of the card tracks was not carried over${round === 1 ? "" : ` after round ${round - 1}`}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3724
|
+
break;
|
|
3725
|
+
}
|
|
3726
|
+
}
|
|
3727
|
+
return {
|
|
3728
|
+
documents,
|
|
3729
|
+
notes
|
|
3730
|
+
};
|
|
3731
|
+
});
|
|
3732
|
+
const variables = [];
|
|
3733
|
+
for (const document of found.flatMap((entry) => entry.documents)) if (!variables.some((kept) => kept["key"] === document["key"])) variables.push(document);
|
|
3734
|
+
return {
|
|
3735
|
+
variables,
|
|
3736
|
+
notes: found.flatMap((entry) => entry.notes)
|
|
3737
|
+
};
|
|
3738
|
+
}
|
|
3739
|
+
//#endregion
|
|
3740
|
+
//#region src/host/presets/presets.ts
|
|
3741
|
+
const PRESETS_FOLDER = "presets";
|
|
3742
|
+
const PRESET_FILE = "preset.json";
|
|
3743
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
3744
|
+
const MAX_TEXT = 300;
|
|
3745
|
+
const isPresetName = (name) => NAME.test(name);
|
|
3746
|
+
const presetsDirectory = (root) => join(root, PRESETS_FOLDER);
|
|
3747
|
+
function presetDirectory(root, name) {
|
|
3748
|
+
if (!isPresetName(name)) throw new Error(`"${name}" is not a usable preset name (letters, digits, "-" and "_", up to 64)`);
|
|
3749
|
+
return join(presetsDirectory(root), name);
|
|
3750
|
+
}
|
|
3751
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3752
|
+
function parseHeader(value, problems) {
|
|
3753
|
+
if (!isRecord(value)) {
|
|
3754
|
+
problems.push(`${PRESET_FILE} must be an object`);
|
|
3755
|
+
return { sampling: {} };
|
|
3756
|
+
}
|
|
3757
|
+
const text = (key) => {
|
|
3758
|
+
const field = value[key];
|
|
3759
|
+
if (field === void 0 || field === null) return void 0;
|
|
3760
|
+
if (typeof field !== "string" || field.length > MAX_TEXT) {
|
|
3761
|
+
problems.push(`${PRESET_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
|
|
3762
|
+
return;
|
|
3763
|
+
}
|
|
3764
|
+
return field.trim() || void 0;
|
|
3765
|
+
};
|
|
3766
|
+
const sampling = parseSampling(value["sampling"], `${PRESET_FILE}: sampling`, problems);
|
|
3767
|
+
const title = text("title");
|
|
3768
|
+
const description = text("description");
|
|
3769
|
+
return {
|
|
3770
|
+
...title === void 0 ? {} : { title },
|
|
3771
|
+
...description === void 0 ? {} : { description },
|
|
3772
|
+
sampling
|
|
3773
|
+
};
|
|
3774
|
+
}
|
|
3775
|
+
function readHeader(directory, problems) {
|
|
3776
|
+
const file = join(directory, PRESET_FILE);
|
|
3777
|
+
if (!existsSync(file)) return { sampling: {} };
|
|
3778
|
+
let value;
|
|
3779
|
+
try {
|
|
3780
|
+
value = JSON.parse(readFileSync(file, "utf8"));
|
|
3781
|
+
} catch {
|
|
3782
|
+
problems.push(`${PRESET_FILE} is not valid JSON`);
|
|
3783
|
+
return { sampling: {} };
|
|
3784
|
+
}
|
|
3785
|
+
return parseHeader(value, problems);
|
|
3786
|
+
}
|
|
3787
|
+
/** Reads one preset folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
|
|
3788
|
+
function readPreset(directory, name, shipped = shippedPromptsDirectory()) {
|
|
3789
|
+
if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
|
|
3790
|
+
const problems = [];
|
|
3791
|
+
const header = readHeader(directory, problems);
|
|
3792
|
+
const files = /* @__PURE__ */ new Map();
|
|
3793
|
+
const base = join(directory, PROMPTS_FOLDER);
|
|
3794
|
+
if (existsSync(base)) for (const entry of readdirSync(base, { withFileTypes: true })) {
|
|
3795
|
+
if (!entry.isDirectory() || !LANGUAGE_FOLDER.test(entry.name)) {
|
|
3796
|
+
problems.push(`prompts/${entry.name}: prompts are kept in a folder named by the language, such as en or zh`);
|
|
3797
|
+
continue;
|
|
3798
|
+
}
|
|
3799
|
+
for (const id of listFiles(join(base, entry.name))) {
|
|
3800
|
+
const path = `${entry.name}/${id}.md`;
|
|
3801
|
+
const text = readFileSync(join(base, path), "utf8");
|
|
3802
|
+
const problem = id.startsWith("roleplay/") ? promptProblem(entry.name, id, text, shipped) : `"${id}" is not a prompt of the story`;
|
|
3803
|
+
if (problem !== void 0) problems.push(`prompts/${path}: ${problem}`);
|
|
3804
|
+
else files.set(path, text);
|
|
3805
|
+
}
|
|
3806
|
+
}
|
|
3807
|
+
if (files.size === 0 && problems.length === 0) problems.push("the preset carries no prompts");
|
|
3808
|
+
const paths = [...files.keys()];
|
|
3809
|
+
const ids = [...new Set(paths.map((path) => path.slice(path.indexOf("/") + 1, -3)))].sort((a, b) => a.localeCompare(b));
|
|
3810
|
+
return {
|
|
3811
|
+
summary: {
|
|
3812
|
+
name,
|
|
3813
|
+
title: header.title ?? name,
|
|
3814
|
+
description: header.description ?? "",
|
|
3815
|
+
languages: [...new Set(paths.map((path) => path.split("/")[0]))].sort((a, b) => a.localeCompare(b)),
|
|
3816
|
+
prompts: ids,
|
|
3817
|
+
rules: ids.filter((id) => !PROSE_PROMPTS.includes(id)),
|
|
3818
|
+
sampling: header.sampling,
|
|
3819
|
+
problems
|
|
3820
|
+
},
|
|
3821
|
+
files
|
|
3822
|
+
};
|
|
3823
|
+
}
|
|
3824
|
+
/** Every preset in the library; one that cannot be read is listed with its problems. */
|
|
3825
|
+
function listPresets(root) {
|
|
3826
|
+
const folder = presetsDirectory(root);
|
|
3827
|
+
if (!existsSync(folder)) return [];
|
|
3828
|
+
return readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isPresetName(entry.name)).map((entry) => readPreset(join(folder, entry.name), entry.name)).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
|
|
3829
|
+
}
|
|
3830
|
+
function loadPreset(root, name) {
|
|
3831
|
+
return readPreset(presetDirectory(root, name), name);
|
|
3832
|
+
}
|
|
3833
|
+
const sha = (text) => createHash("sha256").update(text).digest("hex");
|
|
3834
|
+
/**
|
|
3835
|
+
* Makes a preset of the prose prompts a world carries. Nothing is overwritten.
|
|
3836
|
+
* @throws {Error} when the name is taken, the world carries no prose prompt, or what it carries is not acceptable.
|
|
3837
|
+
*/
|
|
3838
|
+
async function savePresetFromWorld(root, worldDirectory, request) {
|
|
3839
|
+
const target = presetDirectory(root, request.name);
|
|
3840
|
+
if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
|
|
3841
|
+
const source = join(worldDirectory, PROMPTS_FOLDER);
|
|
3842
|
+
const found = [];
|
|
3843
|
+
if (existsSync(source)) {
|
|
3844
|
+
for (const entry of readdirSync(source, { withFileTypes: true })) if (entry.isDirectory() && LANGUAGE_FOLDER.test(entry.name)) {
|
|
3845
|
+
for (const id of listFiles(join(source, entry.name))) if (PROSE_PROMPTS.includes(id)) found.push({
|
|
3846
|
+
language: entry.name,
|
|
3847
|
+
id
|
|
3848
|
+
});
|
|
3849
|
+
}
|
|
3850
|
+
}
|
|
3851
|
+
if (found.length === 0) throw new Error("the world carries no prose prompts to make a preset of");
|
|
3852
|
+
const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
|
|
3853
|
+
try {
|
|
3854
|
+
for (const { language, id } of found) {
|
|
3855
|
+
const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
|
|
3856
|
+
await mkdir(dirname(to), { recursive: true });
|
|
3857
|
+
await writeFile(to, readFileSync(join(source, language, `${id}.md`), "utf8"));
|
|
3858
|
+
}
|
|
3859
|
+
const header = {
|
|
3860
|
+
...request.title === void 0 || request.title.trim() === "" ? {} : { title: request.title.trim() },
|
|
3861
|
+
...request.description === void 0 || request.description.trim() === "" ? {} : { description: request.description.trim() },
|
|
3862
|
+
...request.sampling === void 0 || Object.keys(request.sampling).length === 0 ? {} : { sampling: request.sampling }
|
|
3863
|
+
};
|
|
3864
|
+
await writeFile(join(staging, PRESET_FILE), JSON.stringify(header, null, 2));
|
|
3865
|
+
const loaded = readPreset(staging, request.name);
|
|
3866
|
+
if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
|
|
3867
|
+
await mkdir(presetsDirectory(root), { recursive: true });
|
|
3868
|
+
await rename(staging, target);
|
|
3869
|
+
return readPreset(target, request.name);
|
|
3870
|
+
} finally {
|
|
3871
|
+
await rm(staging, {
|
|
3872
|
+
recursive: true,
|
|
3873
|
+
force: true
|
|
3874
|
+
});
|
|
3875
|
+
}
|
|
3876
|
+
}
|
|
3877
|
+
/** Moves a preset out of the library into `<root>/.trash/presets/`. @returns where it went. */
|
|
3878
|
+
async function deletePreset(root, name, now = Date.now) {
|
|
3879
|
+
const directory = presetDirectory(root, name);
|
|
3880
|
+
if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
|
|
3881
|
+
const aside = join(root, ".trash", PRESETS_FOLDER, `${name}-${now()}`);
|
|
3882
|
+
await mkdir(dirname(aside), { recursive: true });
|
|
3883
|
+
await rename(directory, aside);
|
|
3884
|
+
return aside;
|
|
3885
|
+
}
|
|
3886
|
+
function headerFile(title, description, sampling) {
|
|
3887
|
+
return `${JSON.stringify({
|
|
3888
|
+
...title === void 0 ? {} : { title },
|
|
3889
|
+
...description === void 0 ? {} : { description },
|
|
3890
|
+
...Object.keys(sampling).length === 0 ? {} : { sampling }
|
|
3891
|
+
}, null, 2)}\n`;
|
|
3892
|
+
}
|
|
3893
|
+
async function writeHeader(directory, text) {
|
|
3894
|
+
const file = join(directory, PRESET_FILE);
|
|
3895
|
+
await writeFile(`${file}.tmp`, text);
|
|
3896
|
+
await rename(`${file}.tmp`, file);
|
|
3897
|
+
}
|
|
3898
|
+
/** Changes what a preset says about itself. @throws {Error} when the preset does not exist or the change is not acceptable; nothing is written then. */
|
|
3899
|
+
async function updatePresetInfo(root, name, change) {
|
|
3900
|
+
const directory = presetDirectory(root, name);
|
|
3901
|
+
if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
|
|
3902
|
+
const current = readHeader(directory, []);
|
|
3903
|
+
const problems = [];
|
|
3904
|
+
const next = parseHeader({
|
|
3905
|
+
title: change.title ?? current.title,
|
|
3906
|
+
description: change.description ?? current.description,
|
|
3907
|
+
sampling: change.sampling ?? current.sampling
|
|
3908
|
+
}, problems);
|
|
3909
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
3910
|
+
await writeHeader(directory, headerFile(next.title, next.description, next.sampling));
|
|
3911
|
+
return readPreset(directory, name);
|
|
3912
|
+
}
|
|
3913
|
+
/**
|
|
3914
|
+
* Makes a preset holding the shipped prose prompts of every language, as a starting point to edit. Nothing is overwritten.
|
|
3915
|
+
* @throws {Error} when the name is taken or the information is not acceptable.
|
|
3916
|
+
*/
|
|
3917
|
+
async function createPresetFromShipped(root, request, shipped = shippedPromptsDirectory()) {
|
|
3918
|
+
const target = presetDirectory(root, request.name);
|
|
3919
|
+
if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
|
|
3920
|
+
const problems = [];
|
|
3921
|
+
const header = parseHeader({
|
|
3922
|
+
title: request.title?.trim(),
|
|
3923
|
+
description: request.description?.trim(),
|
|
3924
|
+
sampling: request.sampling
|
|
3925
|
+
}, problems);
|
|
3926
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
3927
|
+
const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
|
|
3928
|
+
try {
|
|
3929
|
+
for (const language of shippedLanguages(shipped)) for (const id of PROSE_PROMPTS) {
|
|
3930
|
+
const from = join(shipped, language, `${id}.md`);
|
|
3931
|
+
if (!existsSync(from)) continue;
|
|
3932
|
+
const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
|
|
3933
|
+
await mkdir(dirname(to), { recursive: true });
|
|
3934
|
+
await writeFile(to, readFileSync(from, "utf8"));
|
|
3935
|
+
}
|
|
3936
|
+
await mkdir(staging, { recursive: true });
|
|
3937
|
+
await writeHeader(staging, headerFile(header.title, header.description, header.sampling));
|
|
3938
|
+
const loaded = readPreset(staging, request.name);
|
|
3939
|
+
if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
|
|
3940
|
+
await mkdir(presetsDirectory(root), { recursive: true });
|
|
3941
|
+
await rename(staging, target);
|
|
3942
|
+
return readPreset(target, request.name);
|
|
3943
|
+
} finally {
|
|
3944
|
+
await rm(staging, {
|
|
3945
|
+
recursive: true,
|
|
3946
|
+
force: true
|
|
3947
|
+
});
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3950
|
+
/** Makes an empty preset folder that the import is about to fill; it has no prompts yet, so it reads as having problems until it does. */
|
|
3951
|
+
async function reservePreset(root, name, title, sampling = {}) {
|
|
3952
|
+
const target = presetDirectory(root, name);
|
|
3953
|
+
if (existsSync(target)) throw new Error(`there is already a preset "${name}"`);
|
|
3954
|
+
await mkdir(target, { recursive: true });
|
|
3955
|
+
await writeHeader(target, headerFile(title.trim().slice(0, MAX_TEXT) || void 0, void 0, sampling));
|
|
3956
|
+
return target;
|
|
3957
|
+
}
|
|
3958
|
+
/**
|
|
3959
|
+
* Makes a preset that adds guidance to the shipped prompts, in every language the program ships: each prompt keeps its shipped text and the guidance follows it, so that
|
|
3960
|
+
* the prompt keeps naming the tools and values it needs. The guidance is the importer's, in the language it was written in.
|
|
3961
|
+
* @throws {Error} when the name is taken, there is no guidance, or a prompt would not be acceptable; nothing is made then.
|
|
3962
|
+
*/
|
|
3963
|
+
async function createPresetFromGuidance(root, request, guidance, shipped = shippedPromptsDirectory()) {
|
|
3964
|
+
const target = presetDirectory(root, request.name);
|
|
3965
|
+
if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
|
|
3966
|
+
const ids = Object.keys(guidance).filter((id) => (guidance[id]?.length ?? 0) > 0);
|
|
3967
|
+
if (ids.length === 0) throw new Error("there is no guidance to make a preset of");
|
|
3968
|
+
const problems = [];
|
|
3969
|
+
const header = parseHeader({
|
|
3970
|
+
title: request.title?.trim(),
|
|
3971
|
+
description: request.description?.trim()
|
|
3972
|
+
}, problems);
|
|
3973
|
+
if (problems.length > 0) throw new Error(problems.join("; "));
|
|
3974
|
+
const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
|
|
3975
|
+
try {
|
|
3976
|
+
for (const language of shippedLanguages(shipped)) for (const id of ids) {
|
|
3977
|
+
const base = readWorldPrompt(join(staging, "none"), language, id, shipped).text.trimEnd();
|
|
3978
|
+
const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
|
|
3979
|
+
await mkdir(dirname(to), { recursive: true });
|
|
3980
|
+
await writeFile(to, `${base}\n\n${(guidance[id] ?? []).join("\n")}\n`);
|
|
3981
|
+
}
|
|
3982
|
+
await writeHeader(staging, headerFile(header.title, header.description, {}));
|
|
3983
|
+
const loaded = readPreset(staging, request.name);
|
|
3984
|
+
if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
|
|
3985
|
+
await mkdir(presetsDirectory(root), { recursive: true });
|
|
3986
|
+
await rename(staging, target);
|
|
3987
|
+
return readPreset(target, request.name);
|
|
3988
|
+
} finally {
|
|
3989
|
+
await rm(staging, {
|
|
3990
|
+
recursive: true,
|
|
3991
|
+
force: true
|
|
3992
|
+
});
|
|
3993
|
+
}
|
|
3994
|
+
}
|
|
3995
|
+
//#endregion
|
|
3996
|
+
export { writeChoices as $, isLeftOut as A, DEFAULT_SLOTS as At, readWorldPrompt as B, pruneMembers as C, parseLoreEdit as Ct, classifyItems as D, LORE_KINDS as Dt, buildRoster as E, parseThingEdit as Et, routeVerdicts as F, withPlayer as G, cleanText as H, yesAt as I, ImportStore as J, IMPORT_FOLDER as K, PROSE_PROMPTS as L, askYesNo as M, mergeReports as N, findEntity as O, LORE_SCOPES as Ot, noAt as P, readImportFolder as Q, deleteWorldPrompt as R, pruneLoreSubjects as S, parseFactionEdit as St, sourcesFor as T, parseRelationEdit as Tt, itemise as U, writeWorldPrompt as V, partsOf as W, openingText as X, PICTURE_FILE as Y, parseChoices as Z, extractStyle as _, parseCharacterFile as _t, isPresetName as a, variableProblems as at, pruneKnowledge as b, InvalidEditProblems as bt, presetDirectory as c, LOCATION_FILE_NAME as ct, savePresetFromWorld as d, SLOTS_FILE_NAME as dt, IMPORT_COMMAND as et, sha as f, parseItemFile as ft, extractEntities as g, CHARACTER_FILE_NAME as gt, emptyExtracted as h, parseFactionFile as ht, deletePreset as i, parseVariablesFile as it, announceProblem as j, INTENT_STATUSES as jt, ROLES as k, WEEKDAY_NAMES as kt, readPreset as l, parseLocationFile as lt, STANDING_PROMPT as m, FACTION_FILE_NAME as mt, createPresetFromGuidance as n, VARIABLES_FILE_NAME as nt, listPresets as o, LORE_FILE_NAME as ot, updatePresetInfo as p, parseSlotsFile as pt, ImportNotFoundError as q, createPresetFromShipped as r, loadVariables as rt, loadPreset as s, parseLoreFile as st, PRESET_FILE as t, parseImportCommand as tt, reservePreset as u, ITEM_FILE_NAME as ut, extractStyleFrom as v, readVariableValues as vt, pruneRelationships as w, parsePlaceEdit as wt, pruneLinks as x, parseCharacterEdit as xt, extractVariables as y, readIdentifier as yt, listWorldPrompts as z };
|
|
3997
|
+
|
|
3998
|
+
//# sourceMappingURL=presets-MwOSMMyu.js.map
|