@dsh-agentic-roleplay/core 0.12.1 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/cordis.patch.yml +108 -0
  2. package/lib/{access-DifaiHrI.js → access-Csp80TFX.js} +2 -2
  3. package/lib/{authoring-tools-VOaXzr_R.js → authoring-tools-hacA5fG-.js} +1910 -1853
  4. package/lib/authoring.js +42 -34
  5. package/lib/{child-DzZ-aI6k.js → child-DTdY14S9.js} +45 -6
  6. package/lib/client.js +830 -571
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +3 -3
  9. package/lib/{dev-context-Bdm-eVer.js → dev-context-Cgv_wZbG.js} +12 -2
  10. package/lib/doctor.js +5 -4
  11. package/lib/{gallery-Ctz-UoFk.js → gallery-BNg0rPTp.js} +3 -3
  12. package/lib/{generator-Cv6WWmZT.js → generator-9-5at9cZ.js} +2 -2
  13. package/lib/helper.js +4 -10
  14. package/lib/{hooks-BdR3mBeM.js → hooks-DlrFO4aQ.js} +216 -45
  15. package/lib/images.js +4 -4
  16. package/lib/index.js +67 -45
  17. package/lib/{jail-Cp4zEfip.js → jail-DVbPSC0R.js} +2 -2
  18. package/lib/{library-BU2A_Dx8.js → library-DTxakw0z.js} +2 -2
  19. package/lib/{lorebook-author-tools-DUKcQu8P.js → lorebook-author-tools-dupq-kb_.js} +6 -6
  20. package/lib/lorebook-authoring.js +7 -6
  21. package/lib/{narration-CDsJ5wxH.js → narration--K2XVIHI.js} +2 -2
  22. package/lib/orchestration.js +12 -12
  23. package/lib/{pack-jail-CzHQu0n3.js → pack-jail-Bq0fzKi4.js} +43 -16
  24. package/lib/{packs-BZ-45J4-.js → packs-D-7EU3yU.js} +2 -2
  25. package/lib/{presenter-agent-C2ZkoxZu.js → presenter-agent-vFOxIuWv.js} +6 -6
  26. package/lib/{preset-BPnRPW-1.js → preset-RHcOG55T.js} +4 -4
  27. package/lib/{preset-author-tools-DBqPwn-o.js → preset-author-tools-Dwxnpv6V.js} +6 -6
  28. package/lib/preset-authoring.js +7 -6
  29. package/lib/{reflection-Cuy0YLv0.js → reflection-DibpEUQK.js} +7 -7
  30. package/lib/{serial-BZNeK57v.js → serial-CDGoXYh-.js} +1317 -1276
  31. package/lib/{turn-guard-xaFxYc1T.js → turn-guard-DDxikrq7.js} +3 -3
  32. package/package.json +4 -3
@@ -1,9 +1,9 @@
1
- import { m as parseSampling } from "./child-DzZ-aI6k.js";
2
- import { f as parseSwitchboard } from "./narration-CDsJ5wxH.js";
3
- import { a as VARIABLE_KINDS, n as atomicWrite, o as VARIABLE_SUBJECTS, s as VARIABLE_VISIBILITIES } from "./access-DifaiHrI.js";
4
- import { G as readDocument, J as errorMessage, K as Reader, X as PROMPTS_FOLDER, Y as LANGUAGE_FOLDER, et as languageOf, it as shippedPromptsDirectory, nt as promptProblem, q as formatIssue, rt as shippedLanguages, tt as listFiles } from "./hooks-BdR3mBeM.js";
1
+ import { m as parseSampling } from "./child-DTdY14S9.js";
2
+ import { f as parseSwitchboard } from "./narration--K2XVIHI.js";
3
+ import { a as VARIABLE_KINDS, n as atomicWrite, o as VARIABLE_SUBJECTS, s as VARIABLE_VISIBILITIES } from "./access-Csp80TFX.js";
4
+ import { G as readDocument, J as errorMessage, K as Reader, X as LANGUAGE_TAG, Y as LANGUAGE_FOLDER, Z as PROMPTS_FOLDER, at as shippedPromptsDirectory, it as shippedLanguages, nt as listFiles, q as formatIssue, rt as promptProblem, tt as languageOf } from "./hooks-DlrFO4aQ.js";
5
5
  import { i as translator, r as languageOf$1 } from "./text-Dfv8S8eq.js";
6
- import { C as slug, S as norm, T as uniqueKey, w as trOf, x as mapLimit } from "./library-BU2A_Dx8.js";
6
+ import { C as slug, S as norm, T as uniqueKey, w as trOf, x as mapLimit } from "./library-DTxakw0z.js";
7
7
  import { dirname, join } from "node:path";
8
8
  import { MAX_ROUTINE_WINDOWS, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, valueIssue } from "@dsh-agentic-roleplay/state";
9
9
  import { existsSync, readFileSync, readdirSync } from "node:fs";
@@ -163,667 +163,115 @@ function guarded(residency, role, service, methods) {
163
163
  return call.bind(target);
164
164
  } });
165
165
  }
166
- // src/shared/world-state.ts
167
- /** The problems with an edit, for the person who made it; nothing was changed. */
168
- var InvalidEditProblems = class extends Error {
169
- problems;
170
- constructor(problems) {
171
- super(`the edit is not acceptable: ${problems.join("; ")}`);
172
- this.problems = problems;
166
+ /**
167
+ * Read an `id` field. Ids are opaque strings, unique within their scope, that
168
+ * stay the same when the file is copied or edited.
169
+ * @param fallback - used when the file sets none.
170
+ */
171
+ function readIdentifier(reader, fallback) {
172
+ const id = reader.string("id") ?? fallback;
173
+ if (id !== void 0 && id.length > 100) reader.fail("id", `must be at most 100 characters`);
174
+ return id;
175
+ }
176
+ // src/host/variables/values.ts
177
+ /** At most this many initial values in one file. */
178
+ const MAX_VALUES = 40;
179
+ /** The `variables` of a world file: what a character, item, place or the world starts with, by the key of each variable. */
180
+ function readVariableValues(reader) {
181
+ const value = reader.raw("variables");
182
+ if (value === void 0 || value === null) return void 0;
183
+ if (typeof value !== "object" || Array.isArray(value)) {
184
+ reader.fail("variables", "must be an object of values by variable key");
185
+ return;
173
186
  }
174
- };
175
- const TEXT_LIMIT = 2e4;
176
- const NAME_LIMIT = 200;
177
- /** Reads an edit from what the browser sent: every unknown or mistyped field is a problem. */
178
- function parseCharacterEdit(value) {
179
- const problems = [];
180
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
181
- const input = value;
182
- const edit = {};
183
- const text = (source, key, path, limit) => {
184
- const found = source[key];
185
- if (found === void 0) return void 0;
186
- if (typeof found !== "string") {
187
- problems.push(`${path}${key} must be text`);
188
- return;
189
- }
190
- if (found.length > limit) {
191
- problems.push(`${path}${key} is longer than ${limit} characters`);
192
- return;
193
- }
194
- return found;
187
+ const entries = Object.entries(value);
188
+ if (entries.length > MAX_VALUES) reader.fail("variables", `at most ${MAX_VALUES} values`);
189
+ const values = {};
190
+ for (const [key, entry] of entries) if (typeof entry === "number" && Number.isFinite(entry) || typeof entry === "boolean" || typeof entry === "string") values[key] = entry;
191
+ else reader.fail(`variables.${key}`, "must be a number, true or false, or text");
192
+ return values;
193
+ }
194
+ const MAX_VISUAL_DESCRIPTION = 2e3;
195
+ /** Read an optional provider-neutral visual identity from an authored entity file. */
196
+ function readVisualIdentity(reader) {
197
+ const visual = reader.object("visual_identity");
198
+ if (visual === void 0) return void 0;
199
+ const description = visual.string("description", { required: true });
200
+ const tags = visual.strings("tags");
201
+ const negativeTags = visual.strings("negative_tags");
202
+ const globalId = visual.string("global_id");
203
+ if (description !== void 0 && description.length > 2e3) visual.fail("description", `must be at most ${MAX_VISUAL_DESCRIPTION} characters`);
204
+ if (tags.length > 40) visual.fail("tags", `has at most 40 entries`);
205
+ if (negativeTags.length > 40) visual.fail("negative_tags", `has at most 40 entries`);
206
+ if (description === void 0) return void 0;
207
+ return {
208
+ description,
209
+ tags,
210
+ negativeTags,
211
+ ...globalId === void 0 ? {} : { globalId }
195
212
  };
196
- const list = (source, key, path) => {
197
- const found = source[key];
198
- if (found === void 0) return void 0;
199
- if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= NAME_LIMIT) || found.length > 50) {
200
- problems.push(`${path}${key} must be a list of short texts`);
201
- return;
202
- }
203
- return found;
213
+ }
214
+ // src/host/characters/character-file.ts
215
+ const CHARACTER_FILE_NAME = "character.json";
216
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}/;
217
+ function readAge(reader) {
218
+ const value = reader.raw("age");
219
+ if (typeof value === "number") {
220
+ if (Number.isFinite(value) && value >= 0) return String(value);
221
+ } else if (value === void 0 || typeof value === "string") return reader.string("age");
222
+ reader.fail("age", "must be a string or a non-negative number");
223
+ }
224
+ function readVector(reader) {
225
+ const axis = (key) => reader.number(key, {
226
+ min: -1,
227
+ max: 1
228
+ }) ?? 0;
229
+ return {
230
+ valence: axis("valence"),
231
+ arousal: axis("arousal"),
232
+ dominance: axis("dominance")
204
233
  };
205
- const choice = (key, options, source = input, path = "") => {
206
- const found = source[key];
207
- if (found === void 0) return void 0;
208
- if (typeof found !== "string" || !options.includes(found)) {
209
- problems.push(`${path}${key} must be one of: ${options.join(", ")}`);
210
- return;
211
- }
212
- return found;
234
+ }
235
+ function readEmotion(reader) {
236
+ if (reader === void 0) return void 0;
237
+ const baselineReader = reader.object("baseline");
238
+ if (baselineReader === void 0) {
239
+ reader.fail("baseline", "is required");
240
+ return;
241
+ }
242
+ const baseline = readVector(baselineReader);
243
+ const immediateReader = reader.object("immediate");
244
+ return {
245
+ baseline,
246
+ immediate: immediateReader === void 0 ? { ...baseline } : readVector(immediateReader)
213
247
  };
214
- const allowed = (source, keys, path) => {
215
- for (const key of Object.keys(source)) if (!keys.includes(key)) problems.push(`${path}${key} is not something that can be edited`);
248
+ }
249
+ function readIntent(reader) {
250
+ const name = reader.string("name", { required: true });
251
+ const deadline = reader.string("deadline");
252
+ const deadlineTime = deadline === void 0 ? void 0 : ISO_DATE.test(deadline) ? Date.parse(deadline) : NaN;
253
+ if (deadline !== void 0 && Number.isNaN(deadlineTime)) reader.fail("deadline", "must be an ISO 8601 date-time");
254
+ const intent = {
255
+ type: reader.oneOf("type", INTENT_TYPES, "agenda"),
256
+ description: reader.text("description"),
257
+ status: reader.oneOf("status", INTENT_STATUSES, "active"),
258
+ horizon: reader.oneOf("horizon", INTENT_HORIZONS, "short"),
259
+ priority: reader.number("priority", {
260
+ min: 0,
261
+ max: 1
262
+ }) ?? .5,
263
+ urgency: reader.number("urgency", {
264
+ min: 0,
265
+ max: 1
266
+ }) ?? .5,
267
+ plan: reader.strings("plan"),
268
+ openThreads: reader.strings("open_threads"),
269
+ constraints: reader.strings("constraints"),
270
+ ...deadlineTime === void 0 || Number.isNaN(deadlineTime) ? {} : { deadline: new Date(deadlineTime).toISOString() }
216
271
  };
217
- allowed(input, [
218
- "name",
219
- "aliases",
220
- "age",
221
- "gender",
222
- "pronouns",
223
- "role",
224
- "tier",
225
- "kind",
226
- "summary",
227
- "personality",
228
- "background",
229
- "appearance",
230
- "voice",
231
- "visualIdentity",
232
- "speech",
233
- "state",
234
- "place",
235
- "goals"
236
- ], "");
237
- const name = text(input, "name", "", NAME_LIMIT);
238
- if (name !== void 0) {
239
- if (name.trim() === "") problems.push("name cannot be blank");
240
- else edit.name = name.trim();
241
- }
242
- const aliases = list(input, "aliases", "");
243
- if (aliases !== void 0) edit.aliases = aliases;
244
- for (const key of [
245
- "age",
246
- "gender",
247
- "pronouns"
248
- ]) {
249
- const found = text(input, key, "", NAME_LIMIT);
250
- if (found !== void 0) edit[key] = found;
251
- }
252
- const voice = text(input, "voice", "", NAME_LIMIT);
253
- if (voice !== void 0) edit.voice = voice;
254
- for (const key of [
255
- "summary",
256
- "personality",
257
- "background",
258
- "appearance"
259
- ]) {
260
- const found = text(input, key, "", TEXT_LIMIT);
261
- if (found !== void 0) edit[key] = found;
262
- }
263
- const role = choice("role", CHARACTER_ROLES);
264
- if (role !== void 0) edit.role = role;
265
- const tier = choice("tier", CHARACTER_TIERS);
266
- if (tier !== void 0) edit.tier = tier;
267
- const kind = choice("kind", CHARACTER_KINDS);
268
- if (kind !== void 0) edit.kind = kind;
269
- const object = (key) => {
270
- const found = input[key];
271
- if (found === void 0) return void 0;
272
- if (typeof found !== "object" || found === null || Array.isArray(found)) {
273
- problems.push(`${key} must be an object`);
274
- return;
275
- }
276
- return found;
277
- };
278
- if (input["visualIdentity"] === null) edit.visualIdentity = null;
279
- else if (input["visualIdentity"] !== void 0) {
280
- const visual = object("visualIdentity");
281
- if (visual !== void 0) {
282
- allowed(visual, [
283
- "description",
284
- "tags",
285
- "negativeTags",
286
- "globalId"
287
- ], "visualIdentity.");
288
- const description = text(visual, "description", "visualIdentity.", 2e3);
289
- const tags = list(visual, "tags", "visualIdentity.");
290
- const negativeTags = list(visual, "negativeTags", "visualIdentity.");
291
- const globalId = text(visual, "globalId", "visualIdentity.", NAME_LIMIT);
292
- if (description === void 0 || description.trim() === "") problems.push("visualIdentity.description is needed");
293
- else edit.visualIdentity = {
294
- description: description.trim(),
295
- tags: tags ?? [],
296
- negativeTags: negativeTags ?? [],
297
- ...globalId === void 0 || globalId.trim() === "" ? {} : { globalId: globalId.trim() }
298
- };
299
- }
300
- }
301
- const speech = object("speech");
302
- if (speech !== void 0) {
303
- allowed(speech, ["style", "examples"], "speech.");
304
- const style = text(speech, "style", "speech.", TEXT_LIMIT);
305
- const examples = list(speech, "examples", "speech.");
306
- edit.speech = {
307
- ...style === void 0 ? {} : { style },
308
- ...examples === void 0 ? {} : { examples }
309
- };
310
- }
311
- const state = object("state");
312
- if (state !== void 0) {
313
- allowed(state, [
314
- "publicState",
315
- "innerState",
316
- "activity"
317
- ], "state.");
318
- edit.state = {};
319
- for (const key of [
320
- "publicState",
321
- "innerState",
322
- "activity"
323
- ]) {
324
- const found = text(state, key, "state.", TEXT_LIMIT);
325
- if (found !== void 0) edit.state[key] = found;
326
- }
327
- }
328
- const place = object("place");
329
- if (place !== void 0) {
330
- allowed(place, ["location", "position"], "place.");
331
- const location = text(place, "location", "place.", NAME_LIMIT);
332
- const position = text(place, "position", "place.", NAME_LIMIT);
333
- if (location === void 0 || location.trim() === "") problems.push("place.location is needed");
334
- else edit.place = {
335
- location,
336
- ...position === void 0 ? {} : { position }
337
- };
338
- }
339
- if (input["goals"] !== void 0) {
340
- if (!Array.isArray(input["goals"])) problems.push("goals must be a list");
341
- else {
342
- const goals = [];
343
- edit.goals = goals;
344
- input["goals"].forEach((entry, index) => {
345
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
346
- problems.push(`goals[${index}] must be an object`);
347
- return;
348
- }
349
- const goal = entry;
350
- const path = `goals[${index}].`;
351
- allowed(goal, [
352
- "ref",
353
- "name",
354
- "description",
355
- "status",
356
- "priority"
357
- ], path);
358
- const ref = text(goal, "ref", path, NAME_LIMIT);
359
- if (ref === void 0) {
360
- problems.push(`${path}ref is needed`);
361
- return;
362
- }
363
- const goalName = text(goal, "name", path, NAME_LIMIT);
364
- if (goalName !== void 0 && goalName.trim() === "") problems.push(`${path}name cannot be blank`);
365
- const description = text(goal, "description", path, TEXT_LIMIT);
366
- const status = choice("status", INTENT_STATUSES, goal, path);
367
- const priority = goal["priority"];
368
- 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`);
369
- goals.push({
370
- ref,
371
- ...goalName === void 0 ? {} : { name: goalName.trim() },
372
- ...description === void 0 ? {} : { description },
373
- ...status === void 0 ? {} : { status },
374
- ...typeof priority === "number" ? { priority } : {}
375
- });
376
- });
377
- }
378
- }
379
- if (problems.length > 0) throw new InvalidEditProblems(problems);
380
- return edit;
381
- }
382
- function parseEntityEdit(value, kind) {
383
- const problems = [];
384
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
385
- const input = value;
386
- const edit = {};
387
- const allowed = kind === "place" ? [
388
- "name",
389
- "description",
390
- "features",
391
- "visualIdentity",
392
- "parent"
393
- ] : [
394
- "name",
395
- "description",
396
- "quantity",
397
- "quality",
398
- "notable",
399
- "hidden",
400
- "containerState",
401
- "visualIdentity",
402
- "owner"
403
- ];
404
- const link = kind === "place" ? "parent" : "owner";
405
- if (link in input) {
406
- const target = input[link];
407
- if (target === null) edit[link] = null;
408
- else if (typeof target !== "string") problems.push(`${link} must be a key or null`);
409
- else edit[link] = target.trim() === "" ? null : target.trim();
410
- }
411
- for (const key of Object.keys(input)) if (!allowed.includes(key)) problems.push(`${key} is not something that can be edited`);
412
- for (const key of [
413
- "name",
414
- "description",
415
- "quality"
416
- ]) {
417
- if (!(key in input)) continue;
418
- const value = input[key];
419
- if (typeof value !== "string" || value.length > (key === "name" ? NAME_LIMIT : TEXT_LIMIT)) problems.push(`${key} must be text`);
420
- else if (key === "name" && value.trim() === "") problems.push("name cannot be blank");
421
- else edit[key] = key === "name" ? value.trim() : value;
422
- }
423
- for (const key of ["notable", "hidden"]) if (key in input) {
424
- if (typeof input[key] !== "boolean") problems.push(`${key} must be true or false`);
425
- else edit[key] = input[key];
426
- }
427
- if ("quantity" in input) {
428
- const quantity = input["quantity"];
429
- if (typeof quantity !== "number" || !Number.isInteger(quantity) || quantity < 1) problems.push("quantity must be a whole number from 1");
430
- else edit["quantity"] = quantity;
431
- }
432
- if ("containerState" in input) {
433
- const state = input["containerState"];
434
- if (state !== "open" && state !== "closed" && state !== "locked") problems.push("containerState must be one of: open, closed, locked");
435
- else edit["containerState"] = state;
436
- }
437
- if ("features" in input) {
438
- const features = input["features"];
439
- 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");
440
- else edit["features"] = features;
441
- }
442
- if (input["visualIdentity"] === null) edit["visualIdentity"] = null;
443
- else if ("visualIdentity" in input) {
444
- const identity = input["visualIdentity"];
445
- if (typeof identity !== "object" || identity === null || Array.isArray(identity)) problems.push("visualIdentity must be an object");
446
- else {
447
- const visual = identity;
448
- const description = visual["description"];
449
- const tags = visual["tags"];
450
- const negativeTags = visual["negativeTags"];
451
- const globalId = visual["globalId"];
452
- if (typeof description !== "string" || description.trim() === "") problems.push("visualIdentity.description is needed");
453
- 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");
454
- else edit["visualIdentity"] = {
455
- description: description.trim(),
456
- tags,
457
- negativeTags,
458
- ...globalId === void 0 || globalId.trim() === "" ? {} : { globalId: globalId.trim() }
459
- };
460
- }
461
- }
462
- if (problems.length > 0) throw new InvalidEditProblems(problems);
463
- return edit;
464
- }
465
- const parsePlaceEdit = (value) => parseEntityEdit(value, "place");
466
- const parseThingEdit = (value) => parseEntityEdit(value, "thing");
467
- function parseFactionEdit(value) {
468
- const problems = [];
469
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
470
- const input = value;
471
- const allowed = [
472
- "name",
473
- "aliases",
474
- "summary",
475
- "description",
476
- "values",
477
- "structure",
478
- "state",
479
- "goals"
480
- ];
481
- for (const key of Object.keys(input)) if (!allowed.includes(key)) problems.push(`${key} is not something that can be edited`);
482
- const edit = {};
483
- for (const key of [
484
- "name",
485
- "summary",
486
- "description",
487
- "structure"
488
- ]) if (key in input) {
489
- const found = input[key];
490
- if (typeof found !== "string" || found.length > TEXT_LIMIT) problems.push(`${key} must be text`);
491
- else if (key === "name" && found.trim() === "") problems.push("name cannot be blank");
492
- else edit[key] = key === "name" ? found.trim() : found;
493
- }
494
- for (const key of ["aliases", "values"]) if (key in input) {
495
- const found = input[key];
496
- if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= NAME_LIMIT)) problems.push(`${key} must be a list of short texts`);
497
- else edit[key] = found;
498
- }
499
- if ("state" in input) {
500
- const state = input["state"];
501
- if (typeof state !== "object" || state === null || Array.isArray(state)) problems.push("state must be an object");
502
- else {
503
- const record = state;
504
- edit.state = {};
505
- for (const key of ["publicState", "innerState"]) if (key in record) {
506
- if (typeof record[key] !== "string") problems.push(`state.${key} must be text`);
507
- else edit.state[key] = record[key];
508
- }
509
- }
510
- }
511
- if ("goals" in input) try {
512
- edit.goals = parseCharacterEdit({ goals: input["goals"] }).goals;
513
- } catch (error) {
514
- if (error instanceof InvalidEditProblems) problems.push(...error.problems);
515
- else throw error;
516
- }
517
- if (problems.length > 0) throw new InvalidEditProblems(problems);
518
- return edit;
519
- }
520
- function parseLoreEdit(value) {
521
- const problems = [];
522
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
523
- const input = value;
524
- const edit = {};
525
- for (const key of Object.keys(input)) if (![
526
- "title",
527
- "kind",
528
- "scope",
529
- "knownBy",
530
- "summary",
531
- "body",
532
- "startsAt",
533
- "endsAt",
534
- "sources"
535
- ].includes(key)) problems.push(`${key} is not something that can be edited`);
536
- for (const key of [
537
- "title",
538
- "summary",
539
- "body"
540
- ]) if (key in input) {
541
- const found = input[key];
542
- if (typeof found !== "string" || found.length > TEXT_LIMIT) problems.push(`${key} must be text`);
543
- else if (key === "title" && found.trim() === "") problems.push("title cannot be blank");
544
- else edit[key] = key === "title" ? found.trim() : found;
545
- }
546
- if ("kind" in input) {
547
- if (typeof input["kind"] !== "string" || !LORE_KINDS.includes(input["kind"])) problems.push(`kind must be one of: ${LORE_KINDS.join(", ")}`);
548
- else edit.kind = input["kind"];
549
- }
550
- if ("scope" in input) {
551
- if (typeof input["scope"] !== "string" || !LORE_SCOPES.includes(input["scope"])) problems.push(`scope must be one of: ${LORE_SCOPES.join(", ")}`);
552
- else edit.scope = input["scope"];
553
- }
554
- if ("knownBy" in input) {
555
- const found = input["knownBy"];
556
- 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");
557
- else edit.knownBy = found.map((entry) => entry.trim());
558
- }
559
- if (edit.scope === "everyone" && (edit.knownBy?.length ?? 0) > 0) problems.push("an entry everyone knows has no list of who knows it");
560
- for (const key of ["startsAt", "endsAt"]) if (key in input) {
561
- const found = input[key];
562
- if (found !== null && (typeof found !== "number" || !Number.isFinite(found))) problems.push(`${key} must be a timestamp or null`);
563
- else edit[key] = found;
564
- }
565
- if ("sources" in input) {
566
- const found = input["sources"];
567
- if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= TEXT_LIMIT)) problems.push("sources must be a list of texts");
568
- else edit.sources = found;
569
- }
570
- const starts = edit.startsAt === null ? void 0 : edit.startsAt;
571
- const ends = edit.endsAt === null ? void 0 : edit.endsAt;
572
- if (starts !== void 0 && ends !== void 0 && ends < starts) problems.push("endsAt must not be before startsAt");
573
- if (problems.length > 0) throw new InvalidEditProblems(problems);
574
- return edit;
575
- }
576
- function parseRelationEdit(value) {
577
- const problems = [];
578
- if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
579
- const input = value;
580
- const kind = input["kind"];
581
- const key = input["key"];
582
- if (![
583
- "character",
584
- "knowledge",
585
- "membership",
586
- "social",
587
- "exit"
588
- ].includes(String(kind))) problems.push("kind is not a relation kind");
589
- const creating = input["create"] === true;
590
- if (!creating && (typeof key !== "string" || key.trim() === "" || key.length > 500)) problems.push("key is needed");
591
- 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");
592
- if ("create" in input && typeof input["create"] !== "boolean") problems.push("create must be true or false");
593
- const allowedByKind = {
594
- character: [
595
- "kind",
596
- "key",
597
- "create",
598
- "from",
599
- "to",
600
- "remove",
601
- "label",
602
- "summary",
603
- "familiarity",
604
- "trust",
605
- "affinity",
606
- "tension"
607
- ],
608
- knowledge: [
609
- "kind",
610
- "key",
611
- "create",
612
- "from",
613
- "toKind",
614
- "to",
615
- "observed",
616
- "remove"
617
- ],
618
- membership: [
619
- "kind",
620
- "key",
621
- "create",
622
- "from",
623
- "to",
624
- "remove",
625
- "role",
626
- "rank",
627
- "status",
628
- "public",
629
- "commitment"
630
- ],
631
- social: [
632
- "kind",
633
- "key",
634
- "create",
635
- "fromKind",
636
- "from",
637
- "toKind",
638
- "to",
639
- "remove",
640
- "label",
641
- "summary",
642
- "familiarity",
643
- "trust",
644
- "affinity",
645
- "tension"
646
- ],
647
- exit: [
648
- "kind",
649
- "key",
650
- "create",
651
- "from",
652
- "to",
653
- "remove",
654
- "description",
655
- "travelSeconds",
656
- "state",
657
- "note"
658
- ]
659
- };
660
- for (const field of Object.keys(input)) if (!(allowedByKind[String(kind)] ?? []).includes(field)) problems.push(`${field} is not something that can be edited`);
661
- if ("remove" in input && typeof input["remove"] !== "boolean") problems.push("remove must be true or false");
662
- for (const field of [
663
- "label",
664
- "summary",
665
- "role",
666
- "rank",
667
- "description",
668
- "note"
669
- ]) if (field in input && (typeof input[field] !== "string" || input[field].length > TEXT_LIMIT)) problems.push(`${field} must be text`);
670
- for (const field of [
671
- "familiarity",
672
- "trust",
673
- "affinity",
674
- "tension",
675
- "commitment"
676
- ]) if (field in input) {
677
- const number = input[field];
678
- const signed = field === "trust" || field === "affinity";
679
- if (typeof number !== "number" || !Number.isFinite(number) || number < (signed ? -1 : 0) || number > 1) problems.push(`${field} must be between ${signed ? "-1" : "0"} and 1`);
680
- }
681
- 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");
682
- if ("public" in input && typeof input["public"] !== "boolean") problems.push("public must be true or false");
683
- if ("observed" in input && typeof input["observed"] !== "boolean") problems.push("observed must be true or false");
684
- if ("status" in input) {
685
- const choices = kind === "exit" ? EXIT_STATES : MEMBERSHIP_STATUSES;
686
- if (typeof input["status"] !== "string" || !choices.includes(input["status"])) problems.push(`status must be one of: ${choices.join(", ")}`);
687
- }
688
- if (creating) {
689
- for (const field of ["from", "to"]) if (typeof input[field] !== "string" || input[field].trim() === "") problems.push(`${field} is needed: the key of the entity, written as plain text and not as an object`);
690
- if ((kind === "character" || kind === "social") && (typeof input["label"] !== "string" || input["label"].trim() === "")) problems.push("label is needed");
691
- if (kind === "membership" && (typeof input["role"] !== "string" || input["role"].trim() === "")) problems.push("role is needed");
692
- if (kind === "exit" && typeof input["description"] !== "string") problems.push("description is needed");
693
- if (kind === "knowledge" && ![
694
- "location",
695
- "item",
696
- "exit"
697
- ].includes(String(input["toKind"]))) problems.push("toKind must be one of: location, item, exit");
698
- if (kind === "social") {
699
- for (const field of ["fromKind", "toKind"]) if (!["character", "faction"].includes(String(input[field]))) problems.push(`${field} must be character or faction`);
700
- }
701
- } else if (kind === "knowledge" && input["remove"] !== true) problems.push("knowledge editing supports creation or removal");
702
- if (problems.length > 0) throw new InvalidEditProblems(problems);
703
- return input;
704
- }
705
- // src/host/folders.ts
706
- /**
707
- * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
708
- * and a missing directory has none; any other failure is thrown.
709
- */
710
- async function subfolders(dir) {
711
- try {
712
- return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
713
- } catch (error) {
714
- if (error.code === "ENOENT") return [];
715
- throw error;
716
- }
717
- }
718
- /**
719
- * Read an `id` field. Ids are opaque strings, unique within their scope, that
720
- * stay the same when the file is copied or edited.
721
- * @param fallback - used when the file sets none.
722
- */
723
- function readIdentifier(reader, fallback) {
724
- const id = reader.string("id") ?? fallback;
725
- if (id !== void 0 && id.length > 100) reader.fail("id", `must be at most 100 characters`);
726
- return id;
727
- }
728
- // src/host/variables/values.ts
729
- /** At most this many initial values in one file. */
730
- const MAX_VALUES = 40;
731
- /** The `variables` of a world file: what a character, item, place or the world starts with, by the key of each variable. */
732
- function readVariableValues(reader) {
733
- const value = reader.raw("variables");
734
- if (value === void 0 || value === null) return void 0;
735
- if (typeof value !== "object" || Array.isArray(value)) {
736
- reader.fail("variables", "must be an object of values by variable key");
737
- return;
738
- }
739
- const entries = Object.entries(value);
740
- if (entries.length > MAX_VALUES) reader.fail("variables", `at most ${MAX_VALUES} values`);
741
- const values = {};
742
- for (const [key, entry] of entries) if (typeof entry === "number" && Number.isFinite(entry) || typeof entry === "boolean" || typeof entry === "string") values[key] = entry;
743
- else reader.fail(`variables.${key}`, "must be a number, true or false, or text");
744
- return values;
745
- }
746
- const MAX_VISUAL_DESCRIPTION = 2e3;
747
- /** Read an optional provider-neutral visual identity from an authored entity file. */
748
- function readVisualIdentity(reader) {
749
- const visual = reader.object("visual_identity");
750
- if (visual === void 0) return void 0;
751
- const description = visual.string("description", { required: true });
752
- const tags = visual.strings("tags");
753
- const negativeTags = visual.strings("negative_tags");
754
- const globalId = visual.string("global_id");
755
- if (description !== void 0 && description.length > 2e3) visual.fail("description", `must be at most ${MAX_VISUAL_DESCRIPTION} characters`);
756
- if (tags.length > 40) visual.fail("tags", `has at most 40 entries`);
757
- if (negativeTags.length > 40) visual.fail("negative_tags", `has at most 40 entries`);
758
- if (description === void 0) return void 0;
759
- return {
760
- description,
761
- tags,
762
- negativeTags,
763
- ...globalId === void 0 ? {} : { globalId }
764
- };
765
- }
766
- // src/host/characters/character-file.ts
767
- const CHARACTER_FILE_NAME = "character.json";
768
- const ISO_DATE = /^\d{4}-\d{2}-\d{2}/;
769
- function readAge(reader) {
770
- const value = reader.raw("age");
771
- if (typeof value === "number") {
772
- if (Number.isFinite(value) && value >= 0) return String(value);
773
- } else if (value === void 0 || typeof value === "string") return reader.string("age");
774
- reader.fail("age", "must be a string or a non-negative number");
775
- }
776
- function readVector(reader) {
777
- const axis = (key) => reader.number(key, {
778
- min: -1,
779
- max: 1
780
- }) ?? 0;
781
- return {
782
- valence: axis("valence"),
783
- arousal: axis("arousal"),
784
- dominance: axis("dominance")
785
- };
786
- }
787
- function readEmotion(reader) {
788
- if (reader === void 0) return void 0;
789
- const baselineReader = reader.object("baseline");
790
- if (baselineReader === void 0) {
791
- reader.fail("baseline", "is required");
792
- return;
793
- }
794
- const baseline = readVector(baselineReader);
795
- const immediateReader = reader.object("immediate");
796
- return {
797
- baseline,
798
- immediate: immediateReader === void 0 ? { ...baseline } : readVector(immediateReader)
799
- };
800
- }
801
- function readIntent(reader) {
802
- const name = reader.string("name", { required: true });
803
- const deadline = reader.string("deadline");
804
- const deadlineTime = deadline === void 0 ? void 0 : ISO_DATE.test(deadline) ? Date.parse(deadline) : NaN;
805
- if (deadline !== void 0 && Number.isNaN(deadlineTime)) reader.fail("deadline", "must be an ISO 8601 date-time");
806
- const intent = {
807
- type: reader.oneOf("type", INTENT_TYPES, "agenda"),
808
- description: reader.text("description"),
809
- status: reader.oneOf("status", INTENT_STATUSES, "active"),
810
- horizon: reader.oneOf("horizon", INTENT_HORIZONS, "short"),
811
- priority: reader.number("priority", {
812
- min: 0,
813
- max: 1
814
- }) ?? .5,
815
- urgency: reader.number("urgency", {
816
- min: 0,
817
- max: 1
818
- }) ?? .5,
819
- plan: reader.strings("plan"),
820
- openThreads: reader.strings("open_threads"),
821
- constraints: reader.strings("constraints"),
822
- ...deadlineTime === void 0 || Number.isNaN(deadlineTime) ? {} : { deadline: new Date(deadlineTime).toISOString() }
823
- };
824
- return name === void 0 ? void 0 : {
825
- ...intent,
826
- name
272
+ return name === void 0 ? void 0 : {
273
+ ...intent,
274
+ name
827
275
  };
828
276
  }
829
277
  const TIME_OF_DAY = /^([01]?\d|2[0-3]):[0-5]\d$/;
@@ -1242,652 +690,1125 @@ function parseSlotsFile(text) {
1242
690
  issues
1243
691
  } : {
1244
692
  ok: true,
1245
- value: slots
693
+ value: slots
694
+ };
695
+ }
696
+ // src/host/locations/location-file.ts
697
+ const LOCATION_FILE_NAME = "location.json";
698
+ const FEATURE_KEY = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]{0,59}$/u;
699
+ function readFeatures(reader) {
700
+ const features = reader.objects("features").flatMap((feature) => {
701
+ const key = feature.string("id", { required: true });
702
+ const name = feature.string("name", { required: true });
703
+ if (key !== void 0 && !FEATURE_KEY.test(key)) feature.fail("id", "must be letters, digits, \"-\" or \"_\", at most 60");
704
+ return key === void 0 || name === void 0 ? [] : [{
705
+ key,
706
+ name,
707
+ description: feature.text("description")
708
+ }];
709
+ });
710
+ const seen = /* @__PURE__ */ new Set();
711
+ features.forEach((feature, index) => {
712
+ if (seen.has(feature.key)) reader.fail(`features[${index}].id`, `"${feature.key}" is used twice in this place`);
713
+ seen.add(feature.key);
714
+ });
715
+ if (features.length > 30) reader.fail("features", `a place has at most 30 features`);
716
+ return features;
717
+ }
718
+ function readExits(reader) {
719
+ const exits = reader.objects("exits").flatMap((exit) => {
720
+ const to = exit.string("to", { required: true });
721
+ const travelSeconds = exit.number("travel_time_seconds", { min: 0 });
722
+ if (travelSeconds !== void 0 && !Number.isInteger(travelSeconds)) exit.fail("travel_time_seconds", "must be a whole number of seconds");
723
+ const back = exit.string("back_description");
724
+ const oneWay = exit.raw("one_way");
725
+ if (oneWay !== void 0 && typeof oneWay !== "boolean") exit.fail("one_way", "must be true or false");
726
+ return to === void 0 ? [] : [{
727
+ to,
728
+ description: exit.text("description"),
729
+ oneWay: oneWay === true,
730
+ ...back === void 0 ? {} : { backDescription: back },
731
+ ...travelSeconds === void 0 || !Number.isInteger(travelSeconds) ? {} : { travelSeconds },
732
+ state: exit.oneOf("state", EXIT_STATES, "open"),
733
+ note: exit.text("note"),
734
+ openedBy: exit.strings("opened_by")
735
+ }];
736
+ });
737
+ if (exits.length > 30) reader.fail("exits", `a place has at most 30 exits`);
738
+ return exits;
739
+ }
740
+ /**
741
+ * Read a `location.json` into the canonical place definition.
742
+ * @param fallbackId - used when the file sets no `id`; the name of its folder.
743
+ */
744
+ function parseLocationFile(text, fallbackId) {
745
+ const issues = [];
746
+ const reader = Reader.fromJson(text, issues);
747
+ if (reader === void 0) return {
748
+ ok: false,
749
+ issues
750
+ };
751
+ const id = readIdentifier(reader, fallbackId) ?? fallbackId;
752
+ const name = reader.string("name", { required: true });
753
+ const parent = reader.string("parent");
754
+ const variables = readVariableValues(reader);
755
+ const visualIdentity = readVisualIdentity(reader);
756
+ const location = {
757
+ id,
758
+ name: name ?? "",
759
+ description: reader.text("description"),
760
+ ...visualIdentity === void 0 ? {} : { visualIdentity },
761
+ ...parent === void 0 ? {} : { parent },
762
+ features: readFeatures(reader),
763
+ exits: readExits(reader),
764
+ ...variables === void 0 ? {} : { variables }
765
+ };
766
+ return issues.length > 0 ? {
767
+ ok: false,
768
+ issues
769
+ } : {
770
+ ok: true,
771
+ value: location
772
+ };
773
+ }
774
+ // src/host/lore/lore-file.ts
775
+ const LORE_FILE_NAME = "lore.json";
776
+ function instant(reader, key) {
777
+ const value = reader.string(key);
778
+ if (value === void 0) return void 0;
779
+ const parsed = Date.parse(value);
780
+ if (!Number.isFinite(parsed)) {
781
+ reader.fail(key, "must be an ISO date or date-time");
782
+ return;
783
+ }
784
+ return parsed;
785
+ }
786
+ function parseLoreFile(text, fallbackId) {
787
+ const issues = [];
788
+ const reader = Reader.fromJson(text, issues);
789
+ if (reader === void 0) return {
790
+ ok: false,
791
+ issues
792
+ };
793
+ const id = readIdentifier(reader, fallbackId) ?? fallbackId;
794
+ const title = reader.string("title", { required: true }) ?? "";
795
+ const subjects = reader.objects("subjects").flatMap((entry) => {
796
+ const kind = entry.oneOf("kind", LORE_SUBJECT_KINDS, "lore");
797
+ const subjectId = entry.string("id", { required: true });
798
+ return subjectId === void 0 ? [] : [{
799
+ kind,
800
+ id: subjectId
801
+ }];
802
+ });
803
+ const startsAt = instant(reader, "starts_at");
804
+ const endsAt = instant(reader, "ends_at");
805
+ if (startsAt !== void 0 && endsAt !== void 0 && endsAt < startsAt) reader.fail("ends_at", "must not be before starts_at");
806
+ const scope = reader.oneOf("scope", LORE_SCOPES, "listed");
807
+ const knownBy = reader.strings("known_by");
808
+ if (scope === "everyone" && knownBy.length > 0) reader.fail("known_by", "applies only to lore whose scope is \"listed\"");
809
+ const value = {
810
+ id,
811
+ title,
812
+ kind: reader.oneOf("kind", LORE_KINDS, "other"),
813
+ scope,
814
+ knownBy,
815
+ summary: reader.text("summary"),
816
+ body: reader.text("body"),
817
+ subjects,
818
+ related: reader.strings("related"),
819
+ sources: reader.strings("sources"),
820
+ ...startsAt === void 0 ? {} : { startsAt },
821
+ ...endsAt === void 0 ? {} : { endsAt }
822
+ };
823
+ return issues.length === 0 ? {
824
+ ok: true,
825
+ value
826
+ } : {
827
+ ok: false,
828
+ issues
829
+ };
830
+ }
831
+ // src/host/variables/load.ts
832
+ const VARIABLES_FILE_NAME = "variables.json";
833
+ function readDefinition(reader) {
834
+ const key = reader.string("key", { required: true });
835
+ const name = reader.string("name", { required: true });
836
+ const kind = reader.oneOf("kind", VARIABLE_KINDS, "number");
837
+ const subject = reader.oneOf("subject", VARIABLE_SUBJECTS, "character");
838
+ const visibility = reader.oneOf("visibility", VARIABLE_VISIBILITIES, "public");
839
+ const min = reader.number("min");
840
+ const max = reader.number("max");
841
+ const defaultValue = reader.raw("default");
842
+ 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");
843
+ const flag = (field) => {
844
+ const value = reader.raw(field);
845
+ if (value !== void 0 && typeof value !== "boolean") reader.fail(field, "must be true or false");
846
+ return typeof value === "boolean" ? value : void 0;
847
+ };
848
+ const integer = flag("integer");
849
+ const baseline = flag("baseline");
850
+ const always = flag("always");
851
+ const bands = reader.objects("bands").flatMap((band) => {
852
+ const upTo = band.number("up_to", {});
853
+ const label = band.string("label", { required: true });
854
+ return upTo === void 0 || label === void 0 ? [] : [{
855
+ upTo,
856
+ label
857
+ }];
858
+ });
859
+ if (key === void 0 || name === void 0) return void 0;
860
+ const only = reader.strings("only");
861
+ const options = reader.strings("options");
862
+ return {
863
+ key,
864
+ name,
865
+ kind,
866
+ subject,
867
+ visibility,
868
+ ...reader.raw("description") === void 0 ? {} : { description: reader.text("description") },
869
+ ...reader.raw("update") === void 0 ? {} : { update: reader.text("update") },
870
+ only,
871
+ options,
872
+ bands,
873
+ ...min === void 0 ? {} : { min },
874
+ ...max === void 0 ? {} : { max },
875
+ ...integer === void 0 ? {} : { integer },
876
+ ...baseline === void 0 ? {} : { baseline },
877
+ ...always === void 0 ? {} : { always },
878
+ ...defaultValue === void 0 || typeof defaultValue === "number" && !Number.isFinite(defaultValue) ? {} : { default: defaultValue }
879
+ };
880
+ }
881
+ /** Read `variables.json`: a list of what the world tracks. */
882
+ function parseVariablesFile(text) {
883
+ const issues = [];
884
+ let data;
885
+ try {
886
+ data = JSON.parse(text.replace(/^/, ""));
887
+ } catch (error) {
888
+ return {
889
+ ok: false,
890
+ issues: [{
891
+ path: "",
892
+ message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
893
+ }]
894
+ };
895
+ }
896
+ if (!Array.isArray(data)) return {
897
+ ok: false,
898
+ issues: [{
899
+ path: "",
900
+ message: "expected a list of variables"
901
+ }]
902
+ };
903
+ const reader = Reader.fromJson(JSON.stringify({ variables: data }), issues);
904
+ if (reader === void 0) return {
905
+ ok: false,
906
+ issues
907
+ };
908
+ const defs = reader.objects("variables").flatMap((entry) => readDefinition(entry) ?? []);
909
+ return issues.length > 0 ? {
910
+ ok: false,
911
+ issues: issues.map((issue) => ({
912
+ ...issue,
913
+ path: issue.path.replace(/^variables/, "")
914
+ }))
915
+ } : {
916
+ ok: true,
917
+ value: defs
1246
918
  };
1247
919
  }
1248
- // src/host/locations/location-file.ts
1249
- const LOCATION_FILE_NAME = "location.json";
1250
- const FEATURE_KEY = /^[\p{L}\p{N}][\p{L}\p{N}\p{M}_-]{0,59}$/u;
1251
- function readFeatures(reader) {
1252
- const features = reader.objects("features").flatMap((feature) => {
1253
- const key = feature.string("id", { required: true });
1254
- const name = feature.string("name", { required: true });
1255
- if (key !== void 0 && !FEATURE_KEY.test(key)) feature.fail("id", "must be letters, digits, \"-\" or \"_\", at most 60");
1256
- return key === void 0 || name === void 0 ? [] : [{
1257
- key,
1258
- name,
1259
- description: feature.text("description")
1260
- }];
1261
- });
1262
- const seen = /* @__PURE__ */ new Set();
1263
- features.forEach((feature, index) => {
1264
- if (seen.has(feature.key)) reader.fail(`features[${index}].id`, `"${feature.key}" is used twice in this place`);
1265
- seen.add(feature.key);
920
+ /** Read the world's own variables: an optional `<world>/variables.json`. A world with none tracks only what every story does. */
921
+ async function loadVariables(worldDir) {
922
+ const result = {
923
+ defs: [],
924
+ problems: []
925
+ };
926
+ const file = join(worldDir, VARIABLES_FILE_NAME);
927
+ try {
928
+ result.defs = await readDocument(file, parseVariablesFile, result.problems) ?? [];
929
+ } catch (error) {
930
+ if (error.code !== "ENOENT") result.problems.push({
931
+ path: file,
932
+ message: errorMessage(error)
933
+ });
934
+ }
935
+ return result;
936
+ }
937
+ /**
938
+ * What is wrong with the variables of a world and the values it starts with, found before anything is created: a
939
+ * declaration that cannot be one, a repeated key, a subject a variable is limited to that does not exist, a value for a
940
+ * variable that is not declared, does not apply to what has it, or is not one it can have.
941
+ */
942
+ function variableProblems(world) {
943
+ const problems = [];
944
+ const scratch = createSessionStore(":memory:", {
945
+ id: "scratch",
946
+ name: "scratch",
947
+ world: {
948
+ id: "scratch",
949
+ name: "scratch"
950
+ }
951
+ }, { vectors: false });
952
+ try {
953
+ const seen = /* @__PURE__ */ new Set();
954
+ world.defs.forEach((def, index) => {
955
+ if (seen.has(def.key)) problems.push(`variables.json[${index}]: "${def.key}" is declared twice`);
956
+ seen.add(def.key);
957
+ try {
958
+ scratch.variables.define(def);
959
+ } catch (error) {
960
+ problems.push(`variables.json[${index}]: ${errorMessage(error)}`);
961
+ }
962
+ });
963
+ const keys = {
964
+ character: new Set(world.characters.map((entry) => entry.id)),
965
+ item: new Set(world.items.map((entry) => entry.id)),
966
+ location: new Set(world.locations.map((entry) => entry.id))
967
+ };
968
+ 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`);
969
+ const check = (kind, who, values) => {
970
+ for (const [key, value] of Object.entries(values ?? {})) {
971
+ const def = scratch.variables.def(key);
972
+ if (def === void 0) {
973
+ problems.push(`${who}: variables.${key}: no such variable is declared (variables.json)`);
974
+ continue;
975
+ }
976
+ if (def.subject !== kind) {
977
+ problems.push(`${who}: variables.${key}: ${def.name} is about ${def.subject === "world" ? "the world" : `a ${def.subject}`}, not ${kind === "world" ? "the world" : `a ${kind}`}`);
978
+ continue;
979
+ }
980
+ 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`);
981
+ const issue = valueIssue(def, value);
982
+ if (issue !== void 0) problems.push(`${who}: variables.${key}: ${issue}`);
983
+ }
984
+ };
985
+ for (const entry of world.characters) check("character", `${entry.id}: character`, entry.variables);
986
+ for (const entry of world.items) check("item", `${entry.id}: item`, entry.variables);
987
+ for (const entry of world.locations) check("location", `${entry.id}: place`, entry.variables);
988
+ check("world", "world.json", world.values);
989
+ } finally {
990
+ scratch.close();
991
+ }
992
+ return problems;
993
+ }
994
+ // src/host/import/dialect.ts
995
+ const MAX_NAMES = 8;
996
+ const PLAIN_MACROS = /* @__PURE__ */ new Set([
997
+ "user",
998
+ "char",
999
+ "bot"
1000
+ ]);
1001
+ const MARKUP = /* @__PURE__ */ new Set([
1002
+ "a",
1003
+ "b",
1004
+ "i",
1005
+ "u",
1006
+ "s",
1007
+ "p",
1008
+ "br",
1009
+ "hr",
1010
+ "em",
1011
+ "strong",
1012
+ "span",
1013
+ "div",
1014
+ "code",
1015
+ "pre",
1016
+ "center",
1017
+ "small",
1018
+ "img",
1019
+ "ul",
1020
+ "ol",
1021
+ "li",
1022
+ "blockquote",
1023
+ "details",
1024
+ "summary",
1025
+ "font",
1026
+ "sub",
1027
+ "sup",
1028
+ "h1",
1029
+ "h2",
1030
+ "h3",
1031
+ "table",
1032
+ "tr",
1033
+ "td",
1034
+ "th"
1035
+ ]);
1036
+ const MACRO = /\{\{\s*([\p{L}_][\p{L}\p{N}_]*)/gu;
1037
+ const BLOCK = /<([\p{L}][\p{L}\p{N}_-]{1,30})(?:\s[^>]*)?>[\s\S]*?<\/\1\s*>/gu;
1038
+ function textsOf(card) {
1039
+ return [
1040
+ card.description,
1041
+ card.personality,
1042
+ card.scenario,
1043
+ card.firstMessage,
1044
+ ...card.alternateGreetings,
1045
+ card.messageExample,
1046
+ card.systemPrompt,
1047
+ card.postHistoryInstructions,
1048
+ ...(card.book?.entries ?? []).map((entry) => entry.content)
1049
+ ];
1050
+ }
1051
+ /** The distinct values of a pattern's first group over some texts, in the order met, lowercased and cut to a few. */
1052
+ function namesIn(texts, pattern, skip) {
1053
+ const found = /* @__PURE__ */ new Set();
1054
+ for (const text of texts) for (const match of text.matchAll(pattern)) {
1055
+ const name = match[1].toLowerCase();
1056
+ if (!skip(name)) found.add(name);
1057
+ }
1058
+ return [...found].slice(0, MAX_NAMES);
1059
+ }
1060
+ /** Reads the machinery of the source tool out of a card: macros, tag blocks and the scripts the reader counted. */
1061
+ function dialectOf(card) {
1062
+ const texts = textsOf(card);
1063
+ return {
1064
+ macros: namesIn(texts, MACRO, (name) => PLAIN_MACROS.has(name)),
1065
+ tags: namesIn(texts, BLOCK, (name) => MARKUP.has(name)),
1066
+ regexScripts: card.ignored.regexScripts ?? 0,
1067
+ helperScripts: card.ignored.helperScripts ?? card.ignored.scripts - (card.ignored.regexScripts ?? 0)
1068
+ };
1069
+ }
1070
+ /** What the person is told about a card before the import starts: what it is, and which of its machinery is left out. */
1071
+ function sourceSummary(card, language) {
1072
+ const tr = translator(languageOf$1(language));
1073
+ const dialect = dialectOf(card);
1074
+ const lines = [tr("The source is a {format} card with {entries} lorebook entries and {greetings} alternate openings.", {
1075
+ format: card.sourceSpec === "chara_card_v2" ? "V2" : "V3",
1076
+ entries: String(card.book?.entries.length ?? 0),
1077
+ greetings: String(card.alternateGreetings.length)
1078
+ })];
1079
+ const left = [
1080
+ ...dialect.regexScripts > 0 ? [tr("{count} regular expressions", { count: String(dialect.regexScripts) })] : [],
1081
+ ...dialect.helperScripts > 0 ? [tr("{count} helper scripts", { count: String(dialect.helperScripts) })] : [],
1082
+ ...dialect.macros.length > 0 ? [tr("macros ({names})", { names: dialect.macros.join(", ") })] : [],
1083
+ ...dialect.tags.length > 0 ? [tr("tag blocks ({names})", { names: dialect.tags.join(", ") })] : []
1084
+ ];
1085
+ if (left.length > 0) lines.push(tr("Nothing runs them, so they are not carried: {parts}. Their effect is kept only where the card also says it in words.", { parts: left.join("; ") }));
1086
+ return lines.join(" ");
1087
+ }
1088
+ // src/host/import/panels.ts
1089
+ const FENCE = /```[^\n]*\n[\s\S]*?```/g;
1090
+ const TAG = /<(\/?)([\p{L}][\p{L}\p{N}_-]*)(?=[\s>/])[^>]*>/gu;
1091
+ const BLOCKS = /* @__PURE__ */ new Set([
1092
+ "div",
1093
+ "table",
1094
+ "details",
1095
+ "pre",
1096
+ "center",
1097
+ "section",
1098
+ "aside",
1099
+ "fieldset"
1100
+ ]);
1101
+ const SEPARATORS = /\s[||│]\s|[||│]\s*\S+\s*[||│]/;
1102
+ const HEADER = /(?:^|\n)[ \t]*(?:【[^】\n]{1,30}】|\[[^\]\n]{1,30}\]|#+[ \t]*[^\n]{1,30})[ \t]*\n?\s*$/;
1103
+ const MAX_HTML_TEXT_CHARS = 600;
1104
+ const MAX_CUSTOM_CHARS = 4e3;
1105
+ /** A block of tags of a card's own invention (not markup) counts as a panel from this many tags: two or three tags are a form of address or an aside, a layout is more. */
1106
+ const MIN_CUSTOM_TAGS = 6;
1107
+ const MAX_PANELS = 6;
1108
+ const collapse = (text) => text.replace(/\n{3,}/g, "\n\n").trim();
1109
+ const plain = (html) => html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
1110
+ /** The outermost elements of block markup and of invented tags in a text, balanced by their own names, with neighbours that only whitespace separates joined into one. */
1111
+ function tagBlocks(text) {
1112
+ const found = [];
1113
+ const open = [];
1114
+ let current = {
1115
+ from: 0,
1116
+ to: 0,
1117
+ custom: false,
1118
+ tags: 0
1119
+ };
1120
+ const closed = new Set([...text.matchAll(TAG)].filter((match) => match[1] === "/").map((match) => match[2].toLowerCase()));
1121
+ for (const match of text.matchAll(TAG)) {
1122
+ const name = match[2].toLowerCase();
1123
+ const custom = !MARKUP.has(name);
1124
+ if (!custom && !BLOCKS.has(name)) continue;
1125
+ if (match[1] === "" && !closed.has(name)) continue;
1126
+ if (match[1] === "") {
1127
+ if (open.length === 0) current = {
1128
+ from: match.index,
1129
+ to: 0,
1130
+ custom: false,
1131
+ tags: 0
1132
+ };
1133
+ open.push(name);
1134
+ current.tags += 1;
1135
+ current.custom ||= custom;
1136
+ } else if (open.includes(name)) {
1137
+ while (open.pop() !== name);
1138
+ current.tags += 1;
1139
+ if (open.length === 0) {
1140
+ current.to = match.index + match[0].length;
1141
+ found.push(current);
1142
+ }
1143
+ }
1144
+ }
1145
+ const joined = [];
1146
+ for (const block of found) {
1147
+ const last = joined.at(-1);
1148
+ if (last !== void 0 && text.slice(last.to, block.from).trim() === "") {
1149
+ last.to = block.to;
1150
+ last.custom ||= block.custom;
1151
+ last.tags += block.tags;
1152
+ } else joined.push({ ...block });
1153
+ }
1154
+ return joined.map((block) => {
1155
+ const header = block.custom ? HEADER.exec(text.slice(0, block.from)) : null;
1156
+ return header === null ? block : {
1157
+ ...block,
1158
+ from: header.index + (header[0].startsWith("\n") ? 1 : 0)
1159
+ };
1266
1160
  });
1267
- if (features.length > 30) reader.fail("features", `a place has at most 30 features`);
1268
- return features;
1269
1161
  }
1270
- function readExits(reader) {
1271
- const exits = reader.objects("exits").flatMap((exit) => {
1272
- const to = exit.string("to", { required: true });
1273
- const travelSeconds = exit.number("travel_time_seconds", { min: 0 });
1274
- if (travelSeconds !== void 0 && !Number.isInteger(travelSeconds)) exit.fail("travel_time_seconds", "must be a whole number of seconds");
1275
- const back = exit.string("back_description");
1276
- const oneWay = exit.raw("one_way");
1277
- if (oneWay !== void 0 && typeof oneWay !== "boolean") exit.fail("one_way", "must be true or false");
1278
- return to === void 0 ? [] : [{
1279
- to,
1280
- description: exit.text("description"),
1281
- oneWay: oneWay === true,
1282
- ...back === void 0 ? {} : { backDescription: back },
1283
- ...travelSeconds === void 0 || !Number.isInteger(travelSeconds) ? {} : { travelSeconds },
1284
- state: exit.oneOf("state", EXIT_STATES, "open"),
1285
- note: exit.text("note"),
1286
- openedBy: exit.strings("opened_by")
1287
- }];
1288
- });
1289
- if (exits.length > 30) reader.fail("exits", `a place has at most 30 exits`);
1290
- return exits;
1162
+ const statusLine = (line) => SEPARATORS.test(line) && /\d/.test(line);
1163
+ /** An update call of a state-tracking framework: a block that holds one is a panel however few tags it has. */
1164
+ const CALL = /\b_\.\w+\(|\bstat_data\b|\bJSONPatch\b/;
1165
+ /** The text before a removed panel without its last line when that line only introduces the panel ("end every reply with this:"). */
1166
+ const withoutLeadIn = (before) => before.replace(/(?:^|\n)[^\n]*[::][ \t]*\n?\s*$/, "\n");
1167
+ function fencesWithoutLeadIn(text, panels) {
1168
+ let out = "";
1169
+ let last = 0;
1170
+ for (const match of text.matchAll(FENCE)) {
1171
+ panels.push(match[0].replace(/^```[^\n]*\n|```$/g, "").trim());
1172
+ out += `${withoutLeadIn(text.slice(last, match.index))}\n\n`;
1173
+ last = match.index + match[0].length;
1174
+ }
1175
+ return out + text.slice(last);
1291
1176
  }
1292
1177
  /**
1293
- * Read a `location.json` into the canonical place definition.
1294
- * @param fallbackId - used when the file sets no `id`; the name of its folder.
1178
+ * Takes the status bars out of a message: fenced code blocks, blocks of tags of the card's own invention (a layout of nested tags, which names may be in any language), short blocks
1179
+ * of markup that carry numbers (when the message has story text besides them: a message wrapped whole in a block is only styled), and closing lines of values set apart by bars.
1180
+ * What is left is the story; the panels are what the card shows its state with.
1295
1181
  */
1296
- function parseLocationFile(text, fallbackId) {
1297
- const issues = [];
1298
- const reader = Reader.fromJson(text, issues);
1299
- if (reader === void 0) return {
1300
- ok: false,
1301
- issues
1302
- };
1303
- const id = readIdentifier(reader, fallbackId) ?? fallbackId;
1304
- const name = reader.string("name", { required: true });
1305
- const parent = reader.string("parent");
1306
- const variables = readVariableValues(reader);
1307
- const visualIdentity = readVisualIdentity(reader);
1308
- const location = {
1309
- id,
1310
- name: name ?? "",
1311
- description: reader.text("description"),
1312
- ...visualIdentity === void 0 ? {} : { visualIdentity },
1313
- ...parent === void 0 ? {} : { parent },
1314
- features: readFeatures(reader),
1315
- exits: readExits(reader),
1316
- ...variables === void 0 ? {} : { variables }
1317
- };
1318
- return issues.length > 0 ? {
1319
- ok: false,
1320
- issues
1321
- } : {
1322
- ok: true,
1323
- value: location
1324
- };
1325
- }
1326
- // src/host/lore/lore-file.ts
1327
- const LORE_FILE_NAME = "lore.json";
1328
- function instant(reader, key) {
1329
- const value = reader.string(key);
1330
- if (value === void 0) return void 0;
1331
- const parsed = Date.parse(value);
1332
- if (!Number.isFinite(parsed)) {
1333
- reader.fail(key, "must be an ISO date or date-time");
1334
- return;
1335
- }
1336
- return parsed;
1337
- }
1338
- function parseLoreFile(text, fallbackId) {
1339
- const issues = [];
1340
- const reader = Reader.fromJson(text, issues);
1341
- if (reader === void 0) return {
1342
- ok: false,
1343
- issues
1344
- };
1345
- const id = readIdentifier(reader, fallbackId) ?? fallbackId;
1346
- const title = reader.string("title", { required: true }) ?? "";
1347
- const subjects = reader.objects("subjects").flatMap((entry) => {
1348
- const kind = entry.oneOf("kind", LORE_SUBJECT_KINDS, "lore");
1349
- const subjectId = entry.string("id", { required: true });
1350
- return subjectId === void 0 ? [] : [{
1351
- kind,
1352
- id: subjectId
1353
- }];
1182
+ function splitPanels(text, options = {}) {
1183
+ const panels = [];
1184
+ let rest = options.leadIn === true ? fencesWithoutLeadIn(text, panels) : text.replace(FENCE, (block) => {
1185
+ panels.push(block.replace(/^```[^\n]*\n|```$/g, "").trim());
1186
+ return "\n\n";
1354
1187
  });
1355
- const startsAt = instant(reader, "starts_at");
1356
- const endsAt = instant(reader, "ends_at");
1357
- if (startsAt !== void 0 && endsAt !== void 0 && endsAt < startsAt) reader.fail("ends_at", "must not be before starts_at");
1358
- const scope = reader.oneOf("scope", LORE_SCOPES, "listed");
1359
- const knownBy = reader.strings("known_by");
1360
- if (scope === "everyone" && knownBy.length > 0) reader.fail("known_by", "applies only to lore whose scope is \"listed\"");
1361
- const value = {
1362
- id,
1363
- title,
1364
- kind: reader.oneOf("kind", LORE_KINDS, "other"),
1365
- scope,
1366
- knownBy,
1367
- summary: reader.text("summary"),
1368
- body: reader.text("body"),
1369
- subjects,
1370
- related: reader.strings("related"),
1371
- sources: reader.strings("sources"),
1372
- ...startsAt === void 0 ? {} : { startsAt },
1373
- ...endsAt === void 0 ? {} : { endsAt }
1374
- };
1375
- return issues.length === 0 ? {
1376
- ok: true,
1377
- value
1378
- } : {
1379
- ok: false,
1380
- issues
1188
+ const blocks = tagBlocks(rest);
1189
+ const outside = blocks.reduceRight((left, { from, to }) => left.slice(0, from) + left.slice(to), rest);
1190
+ if (blocks.length > 0 && (options.alone === true || plain(outside) !== "")) for (const block of [...blocks].reverse()) {
1191
+ const body = rest.slice(block.from, block.to);
1192
+ if (!(block.custom ? (block.tags >= MIN_CUSTOM_TAGS || CALL.test(body)) && body.length <= MAX_CUSTOM_CHARS : plain(body).length <= MAX_HTML_TEXT_CHARS && /\d/.test(body))) continue;
1193
+ panels.unshift(body.trim());
1194
+ rest = (options.leadIn === true ? withoutLeadIn(rest.slice(0, block.from)) : rest.slice(0, block.from)) + "\n\n" + rest.slice(block.to);
1195
+ }
1196
+ const paragraphs = collapse(rest).split(/\n{2,}/);
1197
+ while (paragraphs.length > 1 && paragraphs.at(-1).split("\n").every(statusLine)) panels.push(paragraphs.pop().trim());
1198
+ return {
1199
+ prose: collapse(paragraphs.join("\n\n")),
1200
+ panels: panels.filter((panel) => panel !== "")
1381
1201
  };
1382
1202
  }
1383
- // src/host/lore/load.ts
1384
- const LORE_DIR = "lore";
1385
- async function loadLore(worldDir) {
1386
- const dir = join(worldDir, LORE_DIR);
1387
- const result = {
1388
- lore: [],
1389
- problems: []
1390
- };
1391
- let folders;
1392
- try {
1393
- folders = await subfolders(dir);
1394
- } catch (error) {
1395
- if (error.code !== "ENOENT") result.problems.push({
1396
- path: dir,
1397
- message: errorMessage(error)
1398
- });
1399
- return result;
1400
- }
1401
- const owners = /* @__PURE__ */ new Map();
1402
- for (const folder of folders) {
1403
- const file = join(dir, folder, LORE_FILE_NAME);
1404
- try {
1405
- const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
1406
- if (entry === void 0) continue;
1407
- const owner = owners.get(entry.id);
1408
- if (owner !== void 0) {
1409
- result.problems.push({
1410
- path: file,
1411
- message: `id "${entry.id}" is already used by ${owner}`
1412
- });
1413
- continue;
1414
- }
1415
- owners.set(entry.id, folder);
1416
- result.lore.push(entry);
1417
- } catch (error) {
1418
- if (error.code !== "ENOENT") result.problems.push({
1419
- path: file,
1420
- message: errorMessage(error)
1421
- });
1422
- }
1423
- }
1424
- if (result.lore.length > 500) result.problems.push({
1425
- path: dir,
1426
- message: `a world has at most 500 lore entries`
1427
- });
1428
- return result;
1203
+ /** The distinct panels in a card's own messages (openings and examples): they show which values it keeps and where they start. */
1204
+ function panelsOfCard(card) {
1205
+ const texts = [
1206
+ card.firstMessage,
1207
+ ...card.alternateGreetings,
1208
+ card.messageExample
1209
+ ];
1210
+ return [...new Set(texts.flatMap((text) => splitPanels(text).panels))].filter((panel) => panel.length <= MAX_CUSTOM_CHARS).slice(0, MAX_PANELS);
1429
1211
  }
1430
- // src/host/variables/load.ts
1431
- const VARIABLES_FILE_NAME = "variables.json";
1432
- function readDefinition(reader) {
1433
- const key = reader.string("key", { required: true });
1434
- const name = reader.string("name", { required: true });
1435
- const kind = reader.oneOf("kind", VARIABLE_KINDS, "number");
1436
- const subject = reader.oneOf("subject", VARIABLE_SUBJECTS, "character");
1437
- const visibility = reader.oneOf("visibility", VARIABLE_VISIBILITIES, "public");
1438
- const min = reader.number("min");
1439
- const max = reader.number("max");
1440
- const defaultValue = reader.raw("default");
1441
- 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");
1442
- const flag = (field) => {
1443
- const value = reader.raw(field);
1444
- if (value !== void 0 && typeof value !== "boolean") reader.fail(field, "must be true or false");
1445
- return typeof value === "boolean" ? value : void 0;
1212
+ /** The sentences of one line; a full stop inside a word or a call (`_.set(`) does not end one. */
1213
+ const sentencesOf = (line) => line.match(/(?:[^.!?。!?]|[.!?](?!\s|$))+(?:[.!?]+(?=\s|$)|[。!?]+|$)\s*/gu) ?? [line];
1214
+ const MIN_LEFT_OUT_WORDS = 3;
1215
+ const ECHO_SHARE = .6;
1216
+ /** A short sentence right after a dropped one ("Never skip it.") has nothing left to refer to. */
1217
+ const MAX_TAIL_WORDS = 4;
1218
+ function wordsOf(text) {
1219
+ const words = /* @__PURE__ */ new Set();
1220
+ for (const word of text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []) if (/[㐀-鿿]/.test(word)) for (let index = 0; index < word.length - 1; index += 1) words.add(word.slice(index, index + 2));
1221
+ else if (word.length >= 3) words.add(word);
1222
+ return words;
1223
+ }
1224
+ /**
1225
+ * The sentences of a prose prompt that repeat something the same answer lists as left out. A model that is told to drop an instruction about the shape of the reply (a status bar after
1226
+ * every message) tends to list it and keep it in the same breath; what it listed is not carried.
1227
+ */
1228
+ function withoutLeftOut(prose, leftOut) {
1229
+ const dropped = leftOut.map(wordsOf).filter((words) => words.size >= MIN_LEFT_OUT_WORDS);
1230
+ if (dropped.length === 0) return prose;
1231
+ const echoes = (sentence) => {
1232
+ const words = wordsOf(sentence);
1233
+ return dropped.some((left) => [...left].filter((word) => words.has(word)).length >= left.size * ECHO_SHARE);
1446
1234
  };
1447
- const integer = flag("integer");
1448
- const baseline = flag("baseline");
1449
- const always = flag("always");
1450
- const bands = reader.objects("bands").flatMap((band) => {
1451
- const upTo = band.number("up_to", {});
1452
- const label = band.string("label", { required: true });
1453
- return upTo === void 0 || label === void 0 ? [] : [{
1454
- upTo,
1455
- label
1456
- }];
1457
- });
1458
- if (key === void 0 || name === void 0) return void 0;
1459
- const only = reader.strings("only");
1460
- const options = reader.strings("options");
1461
- return {
1462
- key,
1463
- name,
1464
- kind,
1465
- subject,
1466
- visibility,
1467
- ...reader.raw("description") === void 0 ? {} : { description: reader.text("description") },
1468
- ...reader.raw("update") === void 0 ? {} : { update: reader.text("update") },
1469
- only,
1470
- options,
1471
- bands,
1472
- ...min === void 0 ? {} : { min },
1473
- ...max === void 0 ? {} : { max },
1474
- ...integer === void 0 ? {} : { integer },
1475
- ...baseline === void 0 ? {} : { baseline },
1476
- ...always === void 0 ? {} : { always },
1477
- ...defaultValue === void 0 || typeof defaultValue === "number" && !Number.isFinite(defaultValue) ? {} : { default: defaultValue }
1235
+ const kept = (line) => {
1236
+ let after = false;
1237
+ return sentencesOf(line).filter((sentence) => {
1238
+ const echo = echoes(sentence);
1239
+ const tail = after && sentence.trim().split(/\s+/).length <= MAX_TAIL_WORDS;
1240
+ after = echo;
1241
+ return !echo && !tail;
1242
+ }).join("").trim();
1478
1243
  };
1244
+ return prose.split("\n").map(kept).filter((line) => line !== "").join("\n");
1479
1245
  }
1480
- /** Read `variables.json`: a list of what the world tracks. */
1481
- function parseVariablesFile(text) {
1482
- const issues = [];
1483
- let data;
1484
- try {
1485
- data = JSON.parse(text.replace(/^/, ""));
1486
- } catch (error) {
1487
- return {
1488
- ok: false,
1489
- issues: [{
1490
- path: "",
1491
- message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
1492
- }]
1493
- };
1246
+ const OUTPUT_MARKUP = /<\/?[\p{L}][\p{L}\p{N}_-]*>|```|\b_\.\w+\(|\bstat_data\b|\{\{(?!\s*(?:user|char|bot)\s*\}\})[^{}]+\}\}/u;
1247
+ /** A text that is mostly a panel is a format specification, not a rule or a fact: it goes whole. */
1248
+ const PANEL_SHARE = .5;
1249
+ /** A standing rule without the panel it demands, the sentences that tell the game master to print markup, a code block or an update call after a reply, and the rule itself when the panel was most of it: the story shows its tracked values itself. */
1250
+ function withoutOutputMarkup(passage) {
1251
+ const { prose, panels } = splitPanels(passage, {
1252
+ alone: true,
1253
+ leadIn: true
1254
+ });
1255
+ if (panels.length > 0 && prose.length < passage.length * PANEL_SHARE) return "";
1256
+ return prose.split("\n").map((line) => sentencesOf(line).filter((sentence) => !OUTPUT_MARKUP.test(sentence)).join("").trim()).filter((line) => line !== "").join("\n");
1257
+ }
1258
+ const BARRED = /(?:\s[||│]\s[^||│\n]+){2,}/;
1259
+ /** The first status bar, panel or print-this-markup directive in a text, as written, or nothing: what a world should show with its tracked values rather than carry as text. */
1260
+ function findPanel(text) {
1261
+ const panel = splitPanels(text, { alone: true }).panels[0];
1262
+ if (panel !== void 0) return panel;
1263
+ for (const line of text.split("\n")) for (const sentence of sentencesOf(line)) if (OUTPUT_MARKUP.test(sentence) || BARRED.test(sentence) && /\d/.test(sentence)) return sentence.trim();
1264
+ }
1265
+ // src/shared/import-card.ts
1266
+ /** The command that imports the card waiting in a world, in the world's authoring chat. */
1267
+ const IMPORT_COMMAND = "/import-st";
1268
+ /** What follows the command's name: the card it names, then what the person asks for. The card is always the one in the world's import folder; only the request is passed on. */
1269
+ function importRequestOf(rawInput) {
1270
+ const rest = rawInput.trim();
1271
+ const boundary = rest.search(/\s/u);
1272
+ return boundary < 0 ? "" : rest.slice(boundary).trim();
1273
+ }
1274
+ // src/shared/world-state.ts
1275
+ /** The problems with an edit, for the person who made it; nothing was changed. */
1276
+ var InvalidEditProblems = class extends Error {
1277
+ problems;
1278
+ constructor(problems) {
1279
+ super(`the edit is not acceptable: ${problems.join("; ")}`);
1280
+ this.problems = problems;
1494
1281
  }
1495
- if (!Array.isArray(data)) return {
1496
- ok: false,
1497
- issues: [{
1498
- path: "",
1499
- message: "expected a list of variables"
1500
- }]
1282
+ };
1283
+ const TEXT_LIMIT = 2e4;
1284
+ const NAME_LIMIT = 200;
1285
+ /** Reads an edit from what the browser sent: every unknown or mistyped field is a problem. */
1286
+ function parseCharacterEdit(value) {
1287
+ const problems = [];
1288
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
1289
+ const input = value;
1290
+ const edit = {};
1291
+ const text = (source, key, path, limit) => {
1292
+ const found = source[key];
1293
+ if (found === void 0) return void 0;
1294
+ if (typeof found !== "string") {
1295
+ problems.push(`${path}${key} must be text`);
1296
+ return;
1297
+ }
1298
+ if (found.length > limit) {
1299
+ problems.push(`${path}${key} is longer than ${limit} characters`);
1300
+ return;
1301
+ }
1302
+ return found;
1501
1303
  };
1502
- const reader = Reader.fromJson(JSON.stringify({ variables: data }), issues);
1503
- if (reader === void 0) return {
1504
- ok: false,
1505
- issues
1304
+ const list = (source, key, path) => {
1305
+ const found = source[key];
1306
+ if (found === void 0) return void 0;
1307
+ if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= NAME_LIMIT) || found.length > 50) {
1308
+ problems.push(`${path}${key} must be a list of short texts`);
1309
+ return;
1310
+ }
1311
+ return found;
1506
1312
  };
1507
- const defs = reader.objects("variables").flatMap((entry) => readDefinition(entry) ?? []);
1508
- return issues.length > 0 ? {
1509
- ok: false,
1510
- issues: issues.map((issue) => ({
1511
- ...issue,
1512
- path: issue.path.replace(/^variables/, "")
1513
- }))
1514
- } : {
1515
- ok: true,
1516
- value: defs
1313
+ const choice = (key, options, source = input, path = "") => {
1314
+ const found = source[key];
1315
+ if (found === void 0) return void 0;
1316
+ if (typeof found !== "string" || !options.includes(found)) {
1317
+ problems.push(`${path}${key} must be one of: ${options.join(", ")}`);
1318
+ return;
1319
+ }
1320
+ return found;
1517
1321
  };
1518
- }
1519
- /** Read the world's own variables: an optional `<world>/variables.json`. A world with none tracks only what every story does. */
1520
- async function loadVariables(worldDir) {
1521
- const result = {
1522
- defs: [],
1523
- problems: []
1322
+ const allowed = (source, keys, path) => {
1323
+ for (const key of Object.keys(source)) if (!keys.includes(key)) problems.push(`${path}${key} is not something that can be edited`);
1524
1324
  };
1525
- const file = join(worldDir, VARIABLES_FILE_NAME);
1526
- try {
1527
- result.defs = await readDocument(file, parseVariablesFile, result.problems) ?? [];
1528
- } catch (error) {
1529
- if (error.code !== "ENOENT") result.problems.push({
1530
- path: file,
1531
- message: errorMessage(error)
1532
- });
1325
+ allowed(input, [
1326
+ "name",
1327
+ "aliases",
1328
+ "age",
1329
+ "gender",
1330
+ "pronouns",
1331
+ "role",
1332
+ "tier",
1333
+ "kind",
1334
+ "summary",
1335
+ "personality",
1336
+ "background",
1337
+ "appearance",
1338
+ "voice",
1339
+ "visualIdentity",
1340
+ "speech",
1341
+ "state",
1342
+ "place",
1343
+ "goals"
1344
+ ], "");
1345
+ const name = text(input, "name", "", NAME_LIMIT);
1346
+ if (name !== void 0) {
1347
+ if (name.trim() === "") problems.push("name cannot be blank");
1348
+ else edit.name = name.trim();
1533
1349
  }
1534
- return result;
1535
- }
1536
- /**
1537
- * What is wrong with the variables of a world and the values it starts with, found before anything is created: a
1538
- * declaration that cannot be one, a repeated key, a subject a variable is limited to that does not exist, a value for a
1539
- * variable that is not declared, does not apply to what has it, or is not one it can have.
1540
- */
1541
- function variableProblems(world) {
1542
- const problems = [];
1543
- const scratch = createSessionStore(":memory:", {
1544
- id: "scratch",
1545
- name: "scratch",
1546
- world: {
1547
- id: "scratch",
1548
- name: "scratch"
1350
+ const aliases = list(input, "aliases", "");
1351
+ if (aliases !== void 0) edit.aliases = aliases;
1352
+ for (const key of [
1353
+ "age",
1354
+ "gender",
1355
+ "pronouns"
1356
+ ]) {
1357
+ const found = text(input, key, "", NAME_LIMIT);
1358
+ if (found !== void 0) edit[key] = found;
1359
+ }
1360
+ const voice = text(input, "voice", "", NAME_LIMIT);
1361
+ if (voice !== void 0) edit.voice = voice;
1362
+ for (const key of [
1363
+ "summary",
1364
+ "personality",
1365
+ "background",
1366
+ "appearance"
1367
+ ]) {
1368
+ const found = text(input, key, "", TEXT_LIMIT);
1369
+ if (found !== void 0) edit[key] = found;
1370
+ }
1371
+ const role = choice("role", CHARACTER_ROLES);
1372
+ if (role !== void 0) edit.role = role;
1373
+ const tier = choice("tier", CHARACTER_TIERS);
1374
+ if (tier !== void 0) edit.tier = tier;
1375
+ const kind = choice("kind", CHARACTER_KINDS);
1376
+ if (kind !== void 0) edit.kind = kind;
1377
+ const object = (key) => {
1378
+ const found = input[key];
1379
+ if (found === void 0) return void 0;
1380
+ if (typeof found !== "object" || found === null || Array.isArray(found)) {
1381
+ problems.push(`${key} must be an object`);
1382
+ return;
1383
+ }
1384
+ return found;
1385
+ };
1386
+ if (input["visualIdentity"] === null) edit.visualIdentity = null;
1387
+ else if (input["visualIdentity"] !== void 0) {
1388
+ const visual = object("visualIdentity");
1389
+ if (visual !== void 0) {
1390
+ allowed(visual, [
1391
+ "description",
1392
+ "tags",
1393
+ "negativeTags",
1394
+ "globalId"
1395
+ ], "visualIdentity.");
1396
+ const description = text(visual, "description", "visualIdentity.", 2e3);
1397
+ const tags = list(visual, "tags", "visualIdentity.");
1398
+ const negativeTags = list(visual, "negativeTags", "visualIdentity.");
1399
+ const globalId = text(visual, "globalId", "visualIdentity.", NAME_LIMIT);
1400
+ if (description === void 0 || description.trim() === "") problems.push("visualIdentity.description is needed");
1401
+ else edit.visualIdentity = {
1402
+ description: description.trim(),
1403
+ tags: tags ?? [],
1404
+ negativeTags: negativeTags ?? [],
1405
+ ...globalId === void 0 || globalId.trim() === "" ? {} : { globalId: globalId.trim() }
1406
+ };
1407
+ }
1408
+ }
1409
+ const speech = object("speech");
1410
+ if (speech !== void 0) {
1411
+ allowed(speech, ["style", "examples"], "speech.");
1412
+ const style = text(speech, "style", "speech.", TEXT_LIMIT);
1413
+ const examples = list(speech, "examples", "speech.");
1414
+ edit.speech = {
1415
+ ...style === void 0 ? {} : { style },
1416
+ ...examples === void 0 ? {} : { examples }
1417
+ };
1418
+ }
1419
+ const state = object("state");
1420
+ if (state !== void 0) {
1421
+ allowed(state, [
1422
+ "publicState",
1423
+ "innerState",
1424
+ "activity"
1425
+ ], "state.");
1426
+ edit.state = {};
1427
+ for (const key of [
1428
+ "publicState",
1429
+ "innerState",
1430
+ "activity"
1431
+ ]) {
1432
+ const found = text(state, key, "state.", TEXT_LIMIT);
1433
+ if (found !== void 0) edit.state[key] = found;
1549
1434
  }
1550
- }, { vectors: false });
1551
- try {
1552
- const seen = /* @__PURE__ */ new Set();
1553
- world.defs.forEach((def, index) => {
1554
- if (seen.has(def.key)) problems.push(`variables.json[${index}]: "${def.key}" is declared twice`);
1555
- seen.add(def.key);
1556
- try {
1557
- scratch.variables.define(def);
1558
- } catch (error) {
1559
- problems.push(`variables.json[${index}]: ${errorMessage(error)}`);
1560
- }
1561
- });
1562
- const keys = {
1563
- character: new Set(world.characters.map((entry) => entry.id)),
1564
- item: new Set(world.items.map((entry) => entry.id)),
1565
- location: new Set(world.locations.map((entry) => entry.id))
1435
+ }
1436
+ const place = object("place");
1437
+ if (place !== void 0) {
1438
+ allowed(place, ["location", "position"], "place.");
1439
+ const location = text(place, "location", "place.", NAME_LIMIT);
1440
+ const position = text(place, "position", "place.", NAME_LIMIT);
1441
+ if (location === void 0 || location.trim() === "") problems.push("place.location is needed");
1442
+ else edit.place = {
1443
+ location,
1444
+ ...position === void 0 ? {} : { position }
1566
1445
  };
1567
- 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`);
1568
- const check = (kind, who, values) => {
1569
- for (const [key, value] of Object.entries(values ?? {})) {
1570
- const def = scratch.variables.def(key);
1571
- if (def === void 0) {
1572
- problems.push(`${who}: variables.${key}: no such variable is declared (variables.json)`);
1573
- continue;
1446
+ }
1447
+ if (input["goals"] !== void 0) {
1448
+ if (!Array.isArray(input["goals"])) problems.push("goals must be a list");
1449
+ else {
1450
+ const goals = [];
1451
+ edit.goals = goals;
1452
+ input["goals"].forEach((entry, index) => {
1453
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
1454
+ problems.push(`goals[${index}] must be an object`);
1455
+ return;
1574
1456
  }
1575
- if (def.subject !== kind) {
1576
- problems.push(`${who}: variables.${key}: ${def.name} is about ${def.subject === "world" ? "the world" : `a ${def.subject}`}, not ${kind === "world" ? "the world" : `a ${kind}`}`);
1577
- continue;
1457
+ const goal = entry;
1458
+ const path = `goals[${index}].`;
1459
+ allowed(goal, [
1460
+ "ref",
1461
+ "name",
1462
+ "description",
1463
+ "status",
1464
+ "priority"
1465
+ ], path);
1466
+ const ref = text(goal, "ref", path, NAME_LIMIT);
1467
+ if (ref === void 0) {
1468
+ problems.push(`${path}ref is needed`);
1469
+ return;
1578
1470
  }
1579
- 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`);
1580
- const issue = valueIssue(def, value);
1581
- if (issue !== void 0) problems.push(`${who}: variables.${key}: ${issue}`);
1582
- }
1583
- };
1584
- for (const entry of world.characters) check("character", `${entry.id}: character`, entry.variables);
1585
- for (const entry of world.items) check("item", `${entry.id}: item`, entry.variables);
1586
- for (const entry of world.locations) check("location", `${entry.id}: place`, entry.variables);
1587
- check("world", "world.json", world.values);
1588
- } finally {
1589
- scratch.close();
1590
- }
1591
- return problems;
1592
- }
1593
- // src/host/import/dialect.ts
1594
- const MAX_NAMES = 8;
1595
- const PLAIN_MACROS = /* @__PURE__ */ new Set([
1596
- "user",
1597
- "char",
1598
- "bot"
1599
- ]);
1600
- const MARKUP = /* @__PURE__ */ new Set([
1601
- "a",
1602
- "b",
1603
- "i",
1604
- "u",
1605
- "s",
1606
- "p",
1607
- "br",
1608
- "hr",
1609
- "em",
1610
- "strong",
1611
- "span",
1612
- "div",
1613
- "code",
1614
- "pre",
1615
- "center",
1616
- "small",
1617
- "img",
1618
- "ul",
1619
- "ol",
1620
- "li",
1621
- "blockquote",
1622
- "details",
1623
- "summary",
1624
- "font",
1625
- "sub",
1626
- "sup",
1627
- "h1",
1628
- "h2",
1629
- "h3",
1630
- "table",
1631
- "tr",
1632
- "td",
1633
- "th"
1634
- ]);
1635
- const MACRO = /\{\{\s*([\p{L}_][\p{L}\p{N}_]*)/gu;
1636
- const BLOCK = /<([\p{L}][\p{L}\p{N}_-]{1,30})(?:\s[^>]*)?>[\s\S]*?<\/\1\s*>/gu;
1637
- function textsOf(card) {
1638
- return [
1639
- card.description,
1640
- card.personality,
1641
- card.scenario,
1642
- card.firstMessage,
1643
- ...card.alternateGreetings,
1644
- card.messageExample,
1645
- card.systemPrompt,
1646
- card.postHistoryInstructions,
1647
- ...(card.book?.entries ?? []).map((entry) => entry.content)
1648
- ];
1649
- }
1650
- /** The distinct values of a pattern's first group over some texts, in the order met, lowercased and cut to a few. */
1651
- function namesIn(texts, pattern, skip) {
1652
- const found = /* @__PURE__ */ new Set();
1653
- for (const text of texts) for (const match of text.matchAll(pattern)) {
1654
- const name = match[1].toLowerCase();
1655
- if (!skip(name)) found.add(name);
1656
- }
1657
- return [...found].slice(0, MAX_NAMES);
1658
- }
1659
- /** Reads the machinery of the source tool out of a card: macros, tag blocks and the scripts the reader counted. */
1660
- function dialectOf(card) {
1661
- const texts = textsOf(card);
1662
- return {
1663
- macros: namesIn(texts, MACRO, (name) => PLAIN_MACROS.has(name)),
1664
- tags: namesIn(texts, BLOCK, (name) => MARKUP.has(name)),
1665
- regexScripts: card.ignored.regexScripts ?? 0,
1666
- helperScripts: card.ignored.helperScripts ?? card.ignored.scripts - (card.ignored.regexScripts ?? 0)
1667
- };
1668
- }
1669
- /** What the person is told about a card before the import starts: what it is, and which of its machinery is left out. */
1670
- function sourceSummary(card, language) {
1671
- const tr = translator(languageOf$1(language));
1672
- const dialect = dialectOf(card);
1673
- const lines = [tr("The source is a {format} card with {entries} lorebook entries and {greetings} alternate openings.", {
1674
- format: card.sourceSpec === "chara_card_v2" ? "V2" : "V3",
1675
- entries: String(card.book?.entries.length ?? 0),
1676
- greetings: String(card.alternateGreetings.length)
1677
- })];
1678
- const left = [
1679
- ...dialect.regexScripts > 0 ? [tr("{count} regular expressions", { count: String(dialect.regexScripts) })] : [],
1680
- ...dialect.helperScripts > 0 ? [tr("{count} helper scripts", { count: String(dialect.helperScripts) })] : [],
1681
- ...dialect.macros.length > 0 ? [tr("macros ({names})", { names: dialect.macros.join(", ") })] : [],
1682
- ...dialect.tags.length > 0 ? [tr("tag blocks ({names})", { names: dialect.tags.join(", ") })] : []
1683
- ];
1684
- if (left.length > 0) lines.push(tr("Nothing runs them, so they are not carried: {parts}. Their effect is kept only where the card also says it in words.", { parts: left.join("; ") }));
1685
- return lines.join(" ");
1686
- }
1687
- // src/host/import/panels.ts
1688
- const FENCE = /```[^\n]*\n[\s\S]*?```/g;
1689
- const TAG = /<(\/?)([\p{L}][\p{L}\p{N}_-]*)(?=[\s>/])[^>]*>/gu;
1690
- const BLOCKS = /* @__PURE__ */ new Set([
1691
- "div",
1692
- "table",
1693
- "details",
1694
- "pre",
1695
- "center",
1696
- "section",
1697
- "aside",
1698
- "fieldset"
1699
- ]);
1700
- const SEPARATORS = /\s[||│]\s|[||│]\s*\S+\s*[||│]/;
1701
- const HEADER = /(?:^|\n)[ \t]*(?:【[^】\n]{1,30}】|\[[^\]\n]{1,30}\]|#+[ \t]*[^\n]{1,30})[ \t]*\n?\s*$/;
1702
- const MAX_HTML_TEXT_CHARS = 600;
1703
- const MAX_CUSTOM_CHARS = 4e3;
1704
- /** A block of tags of a card's own invention (not markup) counts as a panel from this many tags: two or three tags are a form of address or an aside, a layout is more. */
1705
- const MIN_CUSTOM_TAGS = 6;
1706
- const MAX_PANELS = 6;
1707
- const collapse = (text) => text.replace(/\n{3,}/g, "\n\n").trim();
1708
- const plain = (html) => html.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
1709
- /** The outermost elements of block markup and of invented tags in a text, balanced by their own names, with neighbours that only whitespace separates joined into one. */
1710
- function tagBlocks(text) {
1711
- const found = [];
1712
- const open = [];
1713
- let current = {
1714
- from: 0,
1715
- to: 0,
1716
- custom: false,
1717
- tags: 0
1718
- };
1719
- const closed = new Set([...text.matchAll(TAG)].filter((match) => match[1] === "/").map((match) => match[2].toLowerCase()));
1720
- for (const match of text.matchAll(TAG)) {
1721
- const name = match[2].toLowerCase();
1722
- const custom = !MARKUP.has(name);
1723
- if (!custom && !BLOCKS.has(name)) continue;
1724
- if (match[1] === "" && !closed.has(name)) continue;
1725
- if (match[1] === "") {
1726
- if (open.length === 0) current = {
1727
- from: match.index,
1728
- to: 0,
1729
- custom: false,
1730
- tags: 0
1731
- };
1732
- open.push(name);
1733
- current.tags += 1;
1734
- current.custom ||= custom;
1735
- } else if (open.includes(name)) {
1736
- while (open.pop() !== name);
1737
- current.tags += 1;
1738
- if (open.length === 0) {
1739
- current.to = match.index + match[0].length;
1740
- found.push(current);
1741
- }
1471
+ const goalName = text(goal, "name", path, NAME_LIMIT);
1472
+ if (goalName !== void 0 && goalName.trim() === "") problems.push(`${path}name cannot be blank`);
1473
+ const description = text(goal, "description", path, TEXT_LIMIT);
1474
+ const status = choice("status", INTENT_STATUSES, goal, path);
1475
+ const priority = goal["priority"];
1476
+ 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`);
1477
+ goals.push({
1478
+ ref,
1479
+ ...goalName === void 0 ? {} : { name: goalName.trim() },
1480
+ ...description === void 0 ? {} : { description },
1481
+ ...status === void 0 ? {} : { status },
1482
+ ...typeof priority === "number" ? { priority } : {}
1483
+ });
1484
+ });
1742
1485
  }
1743
1486
  }
1744
- const joined = [];
1745
- for (const block of found) {
1746
- const last = joined.at(-1);
1747
- if (last !== void 0 && text.slice(last.to, block.from).trim() === "") {
1748
- last.to = block.to;
1749
- last.custom ||= block.custom;
1750
- last.tags += block.tags;
1751
- } else joined.push({ ...block });
1752
- }
1753
- return joined.map((block) => {
1754
- const header = block.custom ? HEADER.exec(text.slice(0, block.from)) : null;
1755
- return header === null ? block : {
1756
- ...block,
1757
- from: header.index + (header[0].startsWith("\n") ? 1 : 0)
1758
- };
1759
- });
1487
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
1488
+ return edit;
1760
1489
  }
1761
- const statusLine = (line) => SEPARATORS.test(line) && /\d/.test(line);
1762
- /** An update call of a state-tracking framework: a block that holds one is a panel however few tags it has. */
1763
- const CALL = /\b_\.\w+\(|\bstat_data\b|\bJSONPatch\b/;
1764
- /** The text before a removed panel without its last line when that line only introduces the panel ("end every reply with this:"). */
1765
- const withoutLeadIn = (before) => before.replace(/(?:^|\n)[^\n]*[::][ \t]*\n?\s*$/, "\n");
1766
- function fencesWithoutLeadIn(text, panels) {
1767
- let out = "";
1768
- let last = 0;
1769
- for (const match of text.matchAll(FENCE)) {
1770
- panels.push(match[0].replace(/^```[^\n]*\n|```$/g, "").trim());
1771
- out += `${withoutLeadIn(text.slice(last, match.index))}\n\n`;
1772
- last = match.index + match[0].length;
1490
+ function parseEntityEdit(value, kind) {
1491
+ const problems = [];
1492
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
1493
+ const input = value;
1494
+ const edit = {};
1495
+ const allowed = kind === "place" ? [
1496
+ "name",
1497
+ "description",
1498
+ "features",
1499
+ "visualIdentity",
1500
+ "parent"
1501
+ ] : [
1502
+ "name",
1503
+ "description",
1504
+ "quantity",
1505
+ "quality",
1506
+ "notable",
1507
+ "hidden",
1508
+ "containerState",
1509
+ "visualIdentity",
1510
+ "owner"
1511
+ ];
1512
+ const link = kind === "place" ? "parent" : "owner";
1513
+ if (link in input) {
1514
+ const target = input[link];
1515
+ if (target === null) edit[link] = null;
1516
+ else if (typeof target !== "string") problems.push(`${link} must be a key or null`);
1517
+ else edit[link] = target.trim() === "" ? null : target.trim();
1773
1518
  }
1774
- return out + text.slice(last);
1775
- }
1776
- /**
1777
- * Takes the status bars out of a message: fenced code blocks, blocks of tags of the card's own invention (a layout of nested tags, which names may be in any language), short blocks
1778
- * of markup that carry numbers (when the message has story text besides them: a message wrapped whole in a block is only styled), and closing lines of values set apart by bars.
1779
- * What is left is the story; the panels are what the card shows its state with.
1780
- */
1781
- function splitPanels(text, options = {}) {
1782
- const panels = [];
1783
- let rest = options.leadIn === true ? fencesWithoutLeadIn(text, panels) : text.replace(FENCE, (block) => {
1784
- panels.push(block.replace(/^```[^\n]*\n|```$/g, "").trim());
1785
- return "\n\n";
1786
- });
1787
- const blocks = tagBlocks(rest);
1788
- const outside = blocks.reduceRight((left, { from, to }) => left.slice(0, from) + left.slice(to), rest);
1789
- if (blocks.length > 0 && (options.alone === true || plain(outside) !== "")) for (const block of [...blocks].reverse()) {
1790
- const body = rest.slice(block.from, block.to);
1791
- if (!(block.custom ? (block.tags >= MIN_CUSTOM_TAGS || CALL.test(body)) && body.length <= MAX_CUSTOM_CHARS : plain(body).length <= MAX_HTML_TEXT_CHARS && /\d/.test(body))) continue;
1792
- panels.unshift(body.trim());
1793
- rest = (options.leadIn === true ? withoutLeadIn(rest.slice(0, block.from)) : rest.slice(0, block.from)) + "\n\n" + rest.slice(block.to);
1519
+ for (const key of Object.keys(input)) if (!allowed.includes(key)) problems.push(`${key} is not something that can be edited`);
1520
+ for (const key of [
1521
+ "name",
1522
+ "description",
1523
+ "quality"
1524
+ ]) {
1525
+ if (!(key in input)) continue;
1526
+ const value = input[key];
1527
+ if (typeof value !== "string" || value.length > (key === "name" ? NAME_LIMIT : TEXT_LIMIT)) problems.push(`${key} must be text`);
1528
+ else if (key === "name" && value.trim() === "") problems.push("name cannot be blank");
1529
+ else edit[key] = key === "name" ? value.trim() : value;
1794
1530
  }
1795
- const paragraphs = collapse(rest).split(/\n{2,}/);
1796
- while (paragraphs.length > 1 && paragraphs.at(-1).split("\n").every(statusLine)) panels.push(paragraphs.pop().trim());
1797
- return {
1798
- prose: collapse(paragraphs.join("\n\n")),
1799
- panels: panels.filter((panel) => panel !== "")
1800
- };
1531
+ for (const key of ["notable", "hidden"]) if (key in input) {
1532
+ if (typeof input[key] !== "boolean") problems.push(`${key} must be true or false`);
1533
+ else edit[key] = input[key];
1534
+ }
1535
+ if ("quantity" in input) {
1536
+ const quantity = input["quantity"];
1537
+ if (typeof quantity !== "number" || !Number.isInteger(quantity) || quantity < 1) problems.push("quantity must be a whole number from 1");
1538
+ else edit["quantity"] = quantity;
1539
+ }
1540
+ if ("containerState" in input) {
1541
+ const state = input["containerState"];
1542
+ if (state !== "open" && state !== "closed" && state !== "locked") problems.push("containerState must be one of: open, closed, locked");
1543
+ else edit["containerState"] = state;
1544
+ }
1545
+ if ("features" in input) {
1546
+ const features = input["features"];
1547
+ 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");
1548
+ else edit["features"] = features;
1549
+ }
1550
+ if (input["visualIdentity"] === null) edit["visualIdentity"] = null;
1551
+ else if ("visualIdentity" in input) {
1552
+ const identity = input["visualIdentity"];
1553
+ if (typeof identity !== "object" || identity === null || Array.isArray(identity)) problems.push("visualIdentity must be an object");
1554
+ else {
1555
+ const visual = identity;
1556
+ const description = visual["description"];
1557
+ const tags = visual["tags"];
1558
+ const negativeTags = visual["negativeTags"];
1559
+ const globalId = visual["globalId"];
1560
+ if (typeof description !== "string" || description.trim() === "") problems.push("visualIdentity.description is needed");
1561
+ 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");
1562
+ else edit["visualIdentity"] = {
1563
+ description: description.trim(),
1564
+ tags,
1565
+ negativeTags,
1566
+ ...globalId === void 0 || globalId.trim() === "" ? {} : { globalId: globalId.trim() }
1567
+ };
1568
+ }
1569
+ }
1570
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
1571
+ return edit;
1801
1572
  }
1802
- /** The distinct panels in a card's own messages (openings and examples): they show which values it keeps and where they start. */
1803
- function panelsOfCard(card) {
1804
- const texts = [
1805
- card.firstMessage,
1806
- ...card.alternateGreetings,
1807
- card.messageExample
1573
+ const parsePlaceEdit = (value) => parseEntityEdit(value, "place");
1574
+ const parseThingEdit = (value) => parseEntityEdit(value, "thing");
1575
+ function parseFactionEdit(value) {
1576
+ const problems = [];
1577
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
1578
+ const input = value;
1579
+ const allowed = [
1580
+ "name",
1581
+ "aliases",
1582
+ "summary",
1583
+ "description",
1584
+ "values",
1585
+ "structure",
1586
+ "state",
1587
+ "goals"
1808
1588
  ];
1809
- return [...new Set(texts.flatMap((text) => splitPanels(text).panels))].filter((panel) => panel.length <= MAX_CUSTOM_CHARS).slice(0, MAX_PANELS);
1810
- }
1811
- /** The sentences of one line; a full stop inside a word or a call (`_.set(`) does not end one. */
1812
- const sentencesOf = (line) => line.match(/(?:[^.!?。!?]|[.!?](?!\s|$))+(?:[.!?]+(?=\s|$)|[。!?]+|$)\s*/gu) ?? [line];
1813
- const MIN_LEFT_OUT_WORDS = 3;
1814
- const ECHO_SHARE = .6;
1815
- /** A short sentence right after a dropped one ("Never skip it.") has nothing left to refer to. */
1816
- const MAX_TAIL_WORDS = 4;
1817
- function wordsOf(text) {
1818
- const words = /* @__PURE__ */ new Set();
1819
- for (const word of text.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []) if (/[㐀-鿿]/.test(word)) for (let index = 0; index < word.length - 1; index += 1) words.add(word.slice(index, index + 2));
1820
- else if (word.length >= 3) words.add(word);
1821
- return words;
1822
- }
1823
- /**
1824
- * The sentences of a prose prompt that repeat something the same answer lists as left out. A model that is told to drop an instruction about the shape of the reply (a status bar after
1825
- * every message) tends to list it and keep it in the same breath; what it listed is not carried.
1826
- */
1827
- function withoutLeftOut(prose, leftOut) {
1828
- const dropped = leftOut.map(wordsOf).filter((words) => words.size >= MIN_LEFT_OUT_WORDS);
1829
- if (dropped.length === 0) return prose;
1830
- const echoes = (sentence) => {
1831
- const words = wordsOf(sentence);
1832
- return dropped.some((left) => [...left].filter((word) => words.has(word)).length >= left.size * ECHO_SHARE);
1833
- };
1834
- const kept = (line) => {
1835
- let after = false;
1836
- return sentencesOf(line).filter((sentence) => {
1837
- const echo = echoes(sentence);
1838
- const tail = after && sentence.trim().split(/\s+/).length <= MAX_TAIL_WORDS;
1839
- after = echo;
1840
- return !echo && !tail;
1841
- }).join("").trim();
1842
- };
1843
- return prose.split("\n").map(kept).filter((line) => line !== "").join("\n");
1844
- }
1845
- const OUTPUT_MARKUP = /<\/?[\p{L}][\p{L}\p{N}_-]*>|```|\b_\.\w+\(|\bstat_data\b|\{\{(?!\s*(?:user|char|bot)\s*\}\})[^{}]+\}\}/u;
1846
- /** A text that is mostly a panel is a format specification, not a rule or a fact: it goes whole. */
1847
- const PANEL_SHARE = .5;
1848
- /** A standing rule without the panel it demands, the sentences that tell the game master to print markup, a code block or an update call after a reply, and the rule itself when the panel was most of it: the story shows its tracked values itself. */
1849
- function withoutOutputMarkup(passage) {
1850
- const { prose, panels } = splitPanels(passage, {
1851
- alone: true,
1852
- leadIn: true
1853
- });
1854
- if (panels.length > 0 && prose.length < passage.length * PANEL_SHARE) return "";
1855
- return prose.split("\n").map((line) => sentencesOf(line).filter((sentence) => !OUTPUT_MARKUP.test(sentence)).join("").trim()).filter((line) => line !== "").join("\n");
1856
- }
1857
- const BARRED = /(?:\s[||│]\s[^||│\n]+){2,}/;
1858
- /** The first status bar, panel or print-this-markup directive in a text, as written, or nothing: what a world should show with its tracked values rather than carry as text. */
1859
- function findPanel(text) {
1860
- const panel = splitPanels(text, { alone: true }).panels[0];
1861
- if (panel !== void 0) return panel;
1862
- for (const line of text.split("\n")) for (const sentence of sentencesOf(line)) if (OUTPUT_MARKUP.test(sentence) || BARRED.test(sentence) && /\d/.test(sentence)) return sentence.trim();
1589
+ for (const key of Object.keys(input)) if (!allowed.includes(key)) problems.push(`${key} is not something that can be edited`);
1590
+ const edit = {};
1591
+ for (const key of [
1592
+ "name",
1593
+ "summary",
1594
+ "description",
1595
+ "structure"
1596
+ ]) if (key in input) {
1597
+ const found = input[key];
1598
+ if (typeof found !== "string" || found.length > TEXT_LIMIT) problems.push(`${key} must be text`);
1599
+ else if (key === "name" && found.trim() === "") problems.push("name cannot be blank");
1600
+ else edit[key] = key === "name" ? found.trim() : found;
1601
+ }
1602
+ for (const key of ["aliases", "values"]) if (key in input) {
1603
+ const found = input[key];
1604
+ if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= NAME_LIMIT)) problems.push(`${key} must be a list of short texts`);
1605
+ else edit[key] = found;
1606
+ }
1607
+ if ("state" in input) {
1608
+ const state = input["state"];
1609
+ if (typeof state !== "object" || state === null || Array.isArray(state)) problems.push("state must be an object");
1610
+ else {
1611
+ const record = state;
1612
+ edit.state = {};
1613
+ for (const key of ["publicState", "innerState"]) if (key in record) {
1614
+ if (typeof record[key] !== "string") problems.push(`state.${key} must be text`);
1615
+ else edit.state[key] = record[key];
1616
+ }
1617
+ }
1618
+ }
1619
+ if ("goals" in input) try {
1620
+ edit.goals = parseCharacterEdit({ goals: input["goals"] }).goals;
1621
+ } catch (error) {
1622
+ if (error instanceof InvalidEditProblems) problems.push(...error.problems);
1623
+ else throw error;
1624
+ }
1625
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
1626
+ return edit;
1863
1627
  }
1864
- // src/shared/authoring-commands.ts
1865
- /** The command a message starts with, when its name is one of `names` (not a longer word that starts with it). */
1866
- function parseAuthoringCommand(text, names) {
1867
- const value = text.trimStart();
1868
- if (!value.startsWith("/")) return void 0;
1869
- const end = value.search(/\s/u);
1870
- const word = (end < 0 ? value : value.slice(0, end)).slice(1).toLowerCase();
1871
- return names.includes(word) ? {
1872
- name: word,
1873
- rest: end < 0 ? "" : value.slice(end).trim()
1874
- } : void 0;
1628
+ function parseLoreEdit(value) {
1629
+ const problems = [];
1630
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
1631
+ const input = value;
1632
+ const edit = {};
1633
+ for (const key of Object.keys(input)) if (![
1634
+ "title",
1635
+ "kind",
1636
+ "scope",
1637
+ "knownBy",
1638
+ "summary",
1639
+ "body",
1640
+ "startsAt",
1641
+ "endsAt",
1642
+ "sources"
1643
+ ].includes(key)) problems.push(`${key} is not something that can be edited`);
1644
+ for (const key of [
1645
+ "title",
1646
+ "summary",
1647
+ "body"
1648
+ ]) if (key in input) {
1649
+ const found = input[key];
1650
+ if (typeof found !== "string" || found.length > TEXT_LIMIT) problems.push(`${key} must be text`);
1651
+ else if (key === "title" && found.trim() === "") problems.push("title cannot be blank");
1652
+ else edit[key] = key === "title" ? found.trim() : found;
1653
+ }
1654
+ if ("kind" in input) {
1655
+ if (typeof input["kind"] !== "string" || !LORE_KINDS.includes(input["kind"])) problems.push(`kind must be one of: ${LORE_KINDS.join(", ")}`);
1656
+ else edit.kind = input["kind"];
1657
+ }
1658
+ if ("scope" in input) {
1659
+ if (typeof input["scope"] !== "string" || !LORE_SCOPES.includes(input["scope"])) problems.push(`scope must be one of: ${LORE_SCOPES.join(", ")}`);
1660
+ else edit.scope = input["scope"];
1661
+ }
1662
+ if ("knownBy" in input) {
1663
+ const found = input["knownBy"];
1664
+ 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");
1665
+ else edit.knownBy = found.map((entry) => entry.trim());
1666
+ }
1667
+ if (edit.scope === "everyone" && (edit.knownBy?.length ?? 0) > 0) problems.push("an entry everyone knows has no list of who knows it");
1668
+ for (const key of ["startsAt", "endsAt"]) if (key in input) {
1669
+ const found = input[key];
1670
+ if (found !== null && (typeof found !== "number" || !Number.isFinite(found))) problems.push(`${key} must be a timestamp or null`);
1671
+ else edit[key] = found;
1672
+ }
1673
+ if ("sources" in input) {
1674
+ const found = input["sources"];
1675
+ if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.length <= TEXT_LIMIT)) problems.push("sources must be a list of texts");
1676
+ else edit.sources = found;
1677
+ }
1678
+ const starts = edit.startsAt === null ? void 0 : edit.startsAt;
1679
+ const ends = edit.endsAt === null ? void 0 : edit.endsAt;
1680
+ if (starts !== void 0 && ends !== void 0 && ends < starts) problems.push("endsAt must not be before startsAt");
1681
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
1682
+ return edit;
1875
1683
  }
1876
- // src/shared/import-card.ts
1877
- /** The message the plugin sends on the player's behalf to start the import in the new world's authoring chat. */
1878
- const IMPORT_COMMAND = "/import-st";
1879
- /** The command in a message, with the card it names, or nothing when the message is not the command. */
1880
- function parseImportCommand(text) {
1881
- const command = parseAuthoringCommand(text, [IMPORT_COMMAND.slice(1)]);
1882
- if (command === void 0) return void 0;
1883
- const boundary = command.rest.search(/\s/u);
1884
- return boundary < 0 ? {
1885
- card: command.rest,
1886
- request: ""
1887
- } : {
1888
- card: command.rest.slice(0, boundary),
1889
- request: command.rest.slice(boundary).trim()
1684
+ function parseRelationEdit(value) {
1685
+ const problems = [];
1686
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new InvalidEditProblems(["the edit must be an object"]);
1687
+ const input = value;
1688
+ const kind = input["kind"];
1689
+ const key = input["key"];
1690
+ if (![
1691
+ "character",
1692
+ "knowledge",
1693
+ "membership",
1694
+ "social",
1695
+ "exit"
1696
+ ].includes(String(kind))) problems.push("kind is not a relation kind");
1697
+ const creating = input["create"] === true;
1698
+ if (!creating && (typeof key !== "string" || key.trim() === "" || key.length > 500)) problems.push("key is needed");
1699
+ 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");
1700
+ if ("create" in input && typeof input["create"] !== "boolean") problems.push("create must be true or false");
1701
+ const allowedByKind = {
1702
+ character: [
1703
+ "kind",
1704
+ "key",
1705
+ "create",
1706
+ "from",
1707
+ "to",
1708
+ "remove",
1709
+ "label",
1710
+ "summary",
1711
+ "familiarity",
1712
+ "trust",
1713
+ "affinity",
1714
+ "tension"
1715
+ ],
1716
+ knowledge: [
1717
+ "kind",
1718
+ "key",
1719
+ "create",
1720
+ "from",
1721
+ "toKind",
1722
+ "to",
1723
+ "observed",
1724
+ "remove"
1725
+ ],
1726
+ membership: [
1727
+ "kind",
1728
+ "key",
1729
+ "create",
1730
+ "from",
1731
+ "to",
1732
+ "remove",
1733
+ "role",
1734
+ "rank",
1735
+ "status",
1736
+ "public",
1737
+ "commitment"
1738
+ ],
1739
+ social: [
1740
+ "kind",
1741
+ "key",
1742
+ "create",
1743
+ "fromKind",
1744
+ "from",
1745
+ "toKind",
1746
+ "to",
1747
+ "remove",
1748
+ "label",
1749
+ "summary",
1750
+ "familiarity",
1751
+ "trust",
1752
+ "affinity",
1753
+ "tension"
1754
+ ],
1755
+ exit: [
1756
+ "kind",
1757
+ "key",
1758
+ "create",
1759
+ "from",
1760
+ "to",
1761
+ "remove",
1762
+ "description",
1763
+ "travelSeconds",
1764
+ "state",
1765
+ "note"
1766
+ ]
1890
1767
  };
1768
+ for (const field of Object.keys(input)) if (!(allowedByKind[String(kind)] ?? []).includes(field)) problems.push(`${field} is not something that can be edited`);
1769
+ if ("remove" in input && typeof input["remove"] !== "boolean") problems.push("remove must be true or false");
1770
+ for (const field of [
1771
+ "label",
1772
+ "summary",
1773
+ "role",
1774
+ "rank",
1775
+ "description",
1776
+ "note"
1777
+ ]) if (field in input && (typeof input[field] !== "string" || input[field].length > TEXT_LIMIT)) problems.push(`${field} must be text`);
1778
+ for (const field of [
1779
+ "familiarity",
1780
+ "trust",
1781
+ "affinity",
1782
+ "tension",
1783
+ "commitment"
1784
+ ]) if (field in input) {
1785
+ const number = input[field];
1786
+ const signed = field === "trust" || field === "affinity";
1787
+ if (typeof number !== "number" || !Number.isFinite(number) || number < (signed ? -1 : 0) || number > 1) problems.push(`${field} must be between ${signed ? "-1" : "0"} and 1`);
1788
+ }
1789
+ 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");
1790
+ if ("public" in input && typeof input["public"] !== "boolean") problems.push("public must be true or false");
1791
+ if ("observed" in input && typeof input["observed"] !== "boolean") problems.push("observed must be true or false");
1792
+ if ("status" in input) {
1793
+ const choices = kind === "exit" ? EXIT_STATES : MEMBERSHIP_STATUSES;
1794
+ if (typeof input["status"] !== "string" || !choices.includes(input["status"])) problems.push(`status must be one of: ${choices.join(", ")}`);
1795
+ }
1796
+ if (creating) {
1797
+ for (const field of ["from", "to"]) if (typeof input[field] !== "string" || input[field].trim() === "") problems.push(`${field} is needed: the key of the entity, written as plain text and not as an object`);
1798
+ if ((kind === "character" || kind === "social") && (typeof input["label"] !== "string" || input["label"].trim() === "")) problems.push("label is needed");
1799
+ if (kind === "membership" && (typeof input["role"] !== "string" || input["role"].trim() === "")) problems.push("role is needed");
1800
+ if (kind === "exit" && typeof input["description"] !== "string") problems.push("description is needed");
1801
+ if (kind === "knowledge" && ![
1802
+ "location",
1803
+ "item",
1804
+ "exit"
1805
+ ].includes(String(input["toKind"]))) problems.push("toKind must be one of: location, item, exit");
1806
+ if (kind === "social") {
1807
+ for (const field of ["fromKind", "toKind"]) if (!["character", "faction"].includes(String(input[field]))) problems.push(`${field} must be character or faction`);
1808
+ }
1809
+ } else if (kind === "knowledge" && input["remove"] !== true) problems.push("knowledge editing supports creation or removal");
1810
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
1811
+ return input;
1891
1812
  }
1892
1813
  // src/host/import/store.ts
1893
1814
  const IMPORT_FOLDER = ".import";
@@ -2137,6 +2058,66 @@ function playerWord(text, name) {
2137
2058
  function withPlayer(text, name) {
2138
2059
  return text.replace(/\[PLAYER\]|\{\{\s*user\s*\}\}/g, playerWord(text, name));
2139
2060
  }
2061
+ // src/host/folders.ts
2062
+ /**
2063
+ * Names of the subfolders of `dir`, sorted. Symbolic links are not followed
2064
+ * and a missing directory has none; any other failure is thrown.
2065
+ */
2066
+ async function subfolders(dir) {
2067
+ try {
2068
+ return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort((a, b) => a.localeCompare(b));
2069
+ } catch (error) {
2070
+ if (error.code === "ENOENT") return [];
2071
+ throw error;
2072
+ }
2073
+ }
2074
+ // src/host/lore/load.ts
2075
+ const LORE_DIR = "lore";
2076
+ async function loadLore(worldDir) {
2077
+ const dir = join(worldDir, LORE_DIR);
2078
+ const result = {
2079
+ lore: [],
2080
+ problems: []
2081
+ };
2082
+ let folders;
2083
+ try {
2084
+ folders = await subfolders(dir);
2085
+ } catch (error) {
2086
+ if (error.code !== "ENOENT") result.problems.push({
2087
+ path: dir,
2088
+ message: errorMessage(error)
2089
+ });
2090
+ return result;
2091
+ }
2092
+ const owners = /* @__PURE__ */ new Map();
2093
+ for (const folder of folders) {
2094
+ const file = join(dir, folder, LORE_FILE_NAME);
2095
+ try {
2096
+ const entry = await readDocument(file, (text) => parseLoreFile(text, folder), result.problems);
2097
+ if (entry === void 0) continue;
2098
+ const owner = owners.get(entry.id);
2099
+ if (owner !== void 0) {
2100
+ result.problems.push({
2101
+ path: file,
2102
+ message: `id "${entry.id}" is already used by ${owner}`
2103
+ });
2104
+ continue;
2105
+ }
2106
+ owners.set(entry.id, folder);
2107
+ result.lore.push(entry);
2108
+ } catch (error) {
2109
+ if (error.code !== "ENOENT") result.problems.push({
2110
+ path: file,
2111
+ message: errorMessage(error)
2112
+ });
2113
+ }
2114
+ }
2115
+ if (result.lore.length > 500) result.problems.push({
2116
+ path: dir,
2117
+ message: `a world has at most 500 lore entries`
2118
+ });
2119
+ return result;
2120
+ }
2140
2121
  // src/host/lorebooks/lorebooks.ts
2141
2122
  const LOREBOOKS_FOLDER = "lorebooks";
2142
2123
  const LOREBOOK_FILE = "lorebook.json";
@@ -2808,6 +2789,7 @@ const TEXT_FIELDS = [
2808
2789
  "timeZone",
2809
2790
  "startingTime",
2810
2791
  "version",
2792
+ "language",
2811
2793
  "preset"
2812
2794
  ];
2813
2795
  const LIST_FIELDS = [
@@ -3113,6 +3095,9 @@ function parseWorldFile(text) {
3113
3095
  const startQuestions = readStartQuestions(reader, alternateOpenings?.length ?? 0);
3114
3096
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
3115
3097
  const sampling = readSampling(reader);
3098
+ const languageText = reader.string("language")?.trim() || void 0;
3099
+ if (languageText !== void 0 && !LANGUAGE_TAG.test(languageText)) reader.fail("language", "must be a language tag such as \"en\", \"zh\", \"ja\" or \"pt-BR\"");
3100
+ const language = languageText !== void 0 && LANGUAGE_TAG.test(languageText) ? languageOf(languageText) : void 0;
3116
3101
  const preset = reader.string("preset")?.trim() || void 0;
3117
3102
  if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
3118
3103
  const lorebooks = reader.strings("lorebooks").map((entry) => entry.trim()).filter((entry) => entry !== "");
@@ -3141,6 +3126,7 @@ function parseWorldFile(text) {
3141
3126
  ...startQuestions === void 0 ? {} : { startQuestions },
3142
3127
  ...narrationVoice === void 0 ? {} : { narrationVoice },
3143
3128
  ...sampling === void 0 ? {} : { sampling },
3129
+ ...language === void 0 ? {} : { language },
3144
3130
  ...preset === void 0 ? {} : { preset },
3145
3131
  ...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
3146
3132
  }
@@ -3960,6 +3946,9 @@ const CHARACTER_SCHEMA = {
3960
3946
  };
3961
3947
  /** The most things one character is given from what the text says it carries. */
3962
3948
  const MAX_CARRIED = 12;
3949
+ const unplacedNote = (character, place) => `${character}: the place "${place}" is not one of the world's places, so the character starts nowhere`;
3950
+ /** Maximum inferred starting places created during one import. */
3951
+ const MAX_STARTING_PLACES = 3;
3963
3952
  /** The document of a character file from what the call answered; names of places and characters become the keys they have in the roster. */
3964
3953
  function characterDocument(entity, answer, roster) {
3965
3954
  const notes = [];
@@ -3997,7 +3986,8 @@ function characterDocument(entity, answer, roster) {
3997
3986
  ["activity", "activity"]
3998
3987
  ]) put(start, to, text(given[from]));
3999
3988
  const place = text(given["location"]) === "" ? void 0 : findEntity(roster, text(given["location"]), "place");
4000
- 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`);
3989
+ const unplaced = text(given["location"]) !== "" && place === void 0 ? text(given["location"]) : void 0;
3990
+ if (unplaced !== void 0) notes.push(unplacedNote(entity.name, unplaced));
4001
3991
  if (place !== void 0) {
4002
3992
  start["location"] = place.key;
4003
3993
  put(start, "position", text(given["position"]));
@@ -4058,6 +4048,7 @@ function characterDocument(entity, answer, roster) {
4058
4048
  return {
4059
4049
  document,
4060
4050
  notes,
4051
+ ...unplaced === void 0 ? {} : { unplaced },
4061
4052
  ...carried.length === 0 ? {} : { carried }
4062
4053
  };
4063
4054
  }
@@ -4589,6 +4580,55 @@ function jobFor(text, tr, entity, sources, roster, card) {
4589
4580
  }
4590
4581
  };
4591
4582
  }
4583
+ /** Creates missing places named by character starting locations. */
4584
+ async function startingPlaces(ctx, card, items, classified, roster, results) {
4585
+ const wanted = /* @__PURE__ */ new Map();
4586
+ for (const { built } of results) {
4587
+ const name = built?.unplaced;
4588
+ if (name === void 0 || /[[\]{}]/.test(name) || name.length > 100 || roster.some((other) => other.kind === "character" && norm(other.name) === norm(name))) continue;
4589
+ const found = wanted.get(norm(name)) ?? {
4590
+ name,
4591
+ who: []
4592
+ };
4593
+ found.who.push(built);
4594
+ wanted.set(norm(name), found);
4595
+ }
4596
+ const made = [];
4597
+ const keys = new Set(roster.map((other) => other.key));
4598
+ for (const { name, who } of [...wanted.values()].slice(0, MAX_STARTING_PLACES)) {
4599
+ const entity = {
4600
+ kind: "place",
4601
+ key: uniqueKey(slug(name, "place"), keys),
4602
+ name,
4603
+ aliases: [],
4604
+ player: false
4605
+ };
4606
+ keys.add(entity.key);
4607
+ const known = [
4608
+ ...roster,
4609
+ ...made.map((each) => each.entity),
4610
+ entity
4611
+ ];
4612
+ ctx.say(`writing place: ${name}`);
4613
+ try {
4614
+ const answer = await ctx.run(jobFor(ctx.text, trOf(ctx), entity, sourcesFor(entity, items, classified), known, card));
4615
+ made.push({
4616
+ entity,
4617
+ built: placeDocument(entity, answer, known)
4618
+ });
4619
+ } catch (error) {
4620
+ for (const character of who) character.notes.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);
4621
+ continue;
4622
+ }
4623
+ for (const character of who) {
4624
+ const start = character.document["start"];
4625
+ start["location"] = entity.key;
4626
+ const at = character.notes.indexOf(unplacedNote(String(character.document["name"]), name));
4627
+ if (at >= 0) character.notes.splice(at, 1);
4628
+ }
4629
+ }
4630
+ return made;
4631
+ }
4592
4632
  /** Makes the documents of every entity of the roster, and the lore from the pieces about the world. */
4593
4633
  async function extractEntities(ctx, card, items, classified, roster) {
4594
4634
  const result = emptyExtracted();
@@ -4613,6 +4653,7 @@ async function extractEntities(ctx, card, items, classified, roster) {
4613
4653
  };
4614
4654
  }
4615
4655
  });
4656
+ entityResults.push(...await startingPlaces(ctx, card, items, classified, roster, entityResults));
4616
4657
  for (const { entity, built, failure } of entityResults) {
4617
4658
  if (failure !== void 0 || built === void 0) {
4618
4659
  result.notes.push(failure ?? `${entity.name}: nothing was written`);
@@ -5138,6 +5179,6 @@ var SerialQueue = class {
5138
5179
  return this.tails.size;
5139
5180
  }
5140
5181
  };
5141
- export { deleteWorldPrompt as $, subfolders as $t, routeVerdicts as A, parseAuthoringCommand as At, createPresetFromGuidance as B, loadLore as Bt, ROLE_TABLE as C, PICTURE_FILE as Ct, mergeReports as D, writeChoices as Dt, askYesNo as E, readImportFolder as Et, parseWorldInfoEdit as F, VARIABLES_FILE_NAME as Ft, loadPreset as G, ITEM_FILE_NAME as Gt, deletePreset as H, parseLoreFile as Ht, combineAnswers as I, loadVariables as It, reservePreset as J, parseSlotsFile as Jt, presetDirectory as K, SLOTS_FILE_NAME as Kt, questionView as L, parseVariablesFile as Lt, WORLD_FILE_NAME as M, splitPanels as Mt, parseWorldFile as N, dialectOf as Nt, modeFor as O, IMPORT_COMMAND as Ot, MAX_OPENING_CHARS as P, sourceSummary as Pt, PROSE_PROMPTS as Q, parseCharacterFile as Qt, startQuestionsToFile as R, variableProblems as Rt, ROLES as S, ImportStore as St, announceProblem as T, parseChoices as Tt, isPresetName as U, LOCATION_FILE_NAME as Ut, createPresetFromShipped as V, LORE_FILE_NAME as Vt, listPresets as W, parseLocationFile as Wt, sha as X, parseFactionFile as Xt, savePresetFromWorld as Y, FACTION_FILE_NAME as Yt, updatePresetInfo as Z, CHARACTER_FILE_NAME as Zt, pruneRelationships as _, itemise as _t, characterDocument as a, parseRelationEdit as an, deleteLorebook as at, classifyItems as b, IMPORT_FOLDER as bt, extractStyle as c, LORE_KINDS as cn, isLorebookName as ct, inert as d, DEFAULT_SLOTS as dn, lorebookDirectory as dt, InvalidEditProblems as en, listWorldPrompts as et, loreDocuments as f, INTENT_STATUSES as fn, readLorebook as ft, pruneMembers as g, cleanText as gt, pruneLoreSubjects as h, writeLorebookEntry as ht, asWritten as i, parsePlaceEdit as in, createLorebook as it, yesAt as j, findPanel as jt, noAt as k, parseImportCommand as kt, extractStyleFrom as l, LORE_SCOPES as ln, listLorebooks as lt, pruneLinks as m, updateLorebookInfo as mt, STANDING_PROMPT as n, parseFactionEdit as nn, writeWorldPrompt as nt, emptyExtracted as o, parseThingEdit as on, deleteLorebookEntry as ot, pruneKnowledge as p, reserveLorebook as pt, readPreset as q, parseItemFile as qt, addLore as r, parseLoreEdit as rn, addLorebookEntries as rt, extractEntities as s, guarded as sn, entriesOf as st, SerialQueue as t, parseCharacterEdit as tn, readWorldPrompt as tt, extractVariables as u, WEEKDAY_NAMES as un, loadLorebook as ut, sourcesFor as v, partsOf as vt, isLeftOut as w, openingText as wt, findEntity as x, ImportNotFoundError as xt, buildRoster as y, withPlayer as yt, PRESET_FILE as z, LORE_DIR as zt };
5182
+ export { deleteWorldPrompt as $, SLOTS_FILE_NAME as $t, routeVerdicts as A, writeChoices as At, createPresetFromGuidance as B, findPanel as Bt, ROLE_TABLE as C, IMPORT_FOLDER as Ct, mergeReports as D, openingText as Dt, askYesNo as E, PICTURE_FILE as Et, parseWorldInfoEdit as F, parsePlaceEdit as Ft, loadPreset as G, loadVariables as Gt, deletePreset as H, dialectOf as Ht, combineAnswers as I, parseRelationEdit as It, reservePreset as J, LORE_FILE_NAME as Jt, presetDirectory as K, parseVariablesFile as Kt, questionView as L, parseThingEdit as Lt, WORLD_FILE_NAME as M, parseCharacterEdit as Mt, parseWorldFile as N, parseFactionEdit as Nt, modeFor as O, parseChoices as Ot, MAX_OPENING_CHARS as P, parseLoreEdit as Pt, PROSE_PROMPTS as Q, ITEM_FILE_NAME as Qt, startQuestionsToFile as R, IMPORT_COMMAND as Rt, ROLES as S, withPlayer as St, announceProblem as T, ImportStore as Tt, isPresetName as U, sourceSummary as Ut, createPresetFromShipped as V, splitPanels as Vt, listPresets as W, VARIABLES_FILE_NAME as Wt, sha as X, LOCATION_FILE_NAME as Xt, savePresetFromWorld as Y, parseLoreFile as Yt, updatePresetInfo as Z, parseLocationFile as Zt, pruneRelationships as _, loadLore as _t, characterDocument as a, parseCharacterFile as an, deleteLorebook as at, classifyItems as b, itemise as bt, extractStyle as c, LORE_SCOPES as cn, isLorebookName as ct, inert as d, INTENT_STATUSES as dn, lorebookDirectory as dt, parseItemFile as en, listWorldPrompts as et, loreDocuments as f, readLorebook as ft, pruneMembers as g, LORE_DIR as gt, pruneLoreSubjects as h, writeLorebookEntry as ht, asWritten as i, CHARACTER_FILE_NAME as in, createLorebook as it, yesAt as j, InvalidEditProblems as jt, noAt as k, readImportFolder as kt, extractStyleFrom as l, WEEKDAY_NAMES as ln, listLorebooks as lt, pruneLinks as m, updateLorebookInfo as mt, STANDING_PROMPT as n, FACTION_FILE_NAME as nn, writeWorldPrompt as nt, emptyExtracted as o, guarded as on, deleteLorebookEntry as ot, pruneKnowledge as p, reserveLorebook as pt, readPreset as q, variableProblems as qt, addLore as r, parseFactionFile as rn, addLorebookEntries as rt, extractEntities as s, LORE_KINDS as sn, entriesOf as st, SerialQueue as t, parseSlotsFile as tn, readWorldPrompt as tt, extractVariables as u, DEFAULT_SLOTS as un, loadLorebook as ut, sourcesFor as v, subfolders as vt, isLeftOut as w, ImportNotFoundError as wt, findEntity as x, partsOf as xt, buildRoster as y, cleanText as yt, PRESET_FILE as z, importRequestOf as zt };
5142
5183
 
5143
- //# sourceMappingURL=serial-BZNeK57v.js.map
5184
+ //# sourceMappingURL=serial-CDGoXYh-.js.map