@dsh-agentic-roleplay/core 0.3.5 → 0.4.0

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 (52) hide show
  1. package/lib/{preset-ClQm7KPQ.js → authoring-tools-C_8ClUkP.js} +542 -261
  2. package/lib/authoring.js +7 -5
  3. package/lib/{child-CFjnaTZt.js → child-DsixtqTw.js} +94 -2
  4. package/lib/client.js +16938 -14212
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/doctor.js +2 -4
  8. package/lib/{gallery-DIEgETzU.js → gallery-CDYKJf_O.js} +2 -2
  9. package/lib/{generator-DJ48HxPI.js → generator-BR1ugzln.js} +2 -2
  10. package/lib/{deliver-Cl6bjp7g.js → hooks-B2EhBS_-.js} +1884 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +1200 -242
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/lorebook-author-tools-C-o0t4dL.js +694 -0
  15. package/lib/lorebook-authoring.js +69 -0
  16. package/lib/{settings-CA6icLL_.js → narration-BT9uvQry.js} +145 -2
  17. package/lib/orchestration.js +34 -21
  18. package/lib/{pack-jail-ClMpVc__.js → pack-jail-soI-In96.js} +170 -12
  19. package/lib/{packs-BC2A3geF.js → packs-CJPSe5LI.js} +7 -4
  20. package/lib/{presenter-agent-DnNEG_Mn.js → presenter-agent-Gu34bZwd.js} +6 -6
  21. package/lib/preset-3zn8xme7.js +242 -0
  22. package/lib/{preset-author-tools-Dibp-LY9.js → preset-author-tools-C-X8G40s.js} +24 -18
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-DNjNxQL5.js → presets-C3mhqqfz.js} +50 -28
  25. package/lib/{reflection-Bju_LPFn.js → reflection-Btsj0ZLh.js} +51 -17
  26. package/package.json +3 -2
  27. package/packs/scene/map.html +1 -0
  28. package/packs/scene/strip.html +1 -0
  29. package/prompts/en/import/lorebook.md +8 -0
  30. package/prompts/en/import/style.md +1 -0
  31. package/prompts/en/lorebook/persona.md +1 -0
  32. package/prompts/en/lorebook/procedure.md +1 -0
  33. package/prompts/en/lorebook/welcome.md +1 -0
  34. package/prompts/en/preset/persona.md +1 -1
  35. package/prompts/en/preset/procedure.md +1 -1
  36. package/prompts/en/roleplay/character-lookup.md +1 -0
  37. package/prompts/en/roleplay/game-master.md +1 -1
  38. package/prompts/en/world/procedure.md +1 -1
  39. package/prompts/zh/import/lorebook.md +8 -0
  40. package/prompts/zh/import/style.md +1 -0
  41. package/prompts/zh/lorebook/persona.md +1 -0
  42. package/prompts/zh/lorebook/procedure.md +1 -0
  43. package/prompts/zh/lorebook/welcome.md +1 -0
  44. package/prompts/zh/preset/persona.md +1 -1
  45. package/prompts/zh/preset/procedure.md +1 -1
  46. package/prompts/zh/roleplay/character-lookup.md +1 -0
  47. package/prompts/zh/roleplay/game-master.md +1 -1
  48. package/prompts/zh/world/procedure.md +1 -1
  49. package/lib/hooks-DdO_tNhu.js +0 -1060
  50. package/lib/language-BgyxtB2h.js +0 -38
  51. package/lib/load-Clkl0T7C.js +0 -486
  52. package/lib/narration-DK2kiIjE.js +0 -141
@@ -1,13 +1,32 @@
1
- import { t as promptFor } from "./access-EbNdZFbk.js";
2
- import "./settings-CA6icLL_.js";
3
- import { T as SessionNotFoundError, r as parsePlotsFile } from "./load-Clkl0T7C.js";
4
- import { n as encodeOutput, r as encodePreview } from "./narration-DK2kiIjE.js";
5
- import { a as runChild, c as addTokens, i as childTrace, n as childSampling, s as NO_TOKENS, t as childModel, u as estimateAnswer } from "./child-CFjnaTZt.js";
6
- import { a as wrongLanguage } from "./language-BgyxtB2h.js";
7
- import { join } from "node:path";
8
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
1
+ import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { a as liveSettings, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-BT9uvQry.js";
3
+ import { a as runChild, d as addTokens, h as trimCharacters, i as childTrace, l as tokensOf, n as childSampling, p as estimateAnswer, t as childModel, u as NO_TOKENS } from "./child-DsixtqTw.js";
4
+ import { dirname, join } from "node:path";
5
+ import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
9
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
10
- import { DAY, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, holidaysOn, isSessionId, localTime, nextTimeOfDay, readCalendar, seasonOf, sessionDatabase } from "@dsh-agentic-roleplay/state";
8
+ import { fileURLToPath } from "node:url";
9
+ import { Service } from "@deepseek-ai/cordis";
10
+ import { readFile, stat } from "node:fs/promises";
11
+ import { DAY, ENGAGEMENT_GRACE, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, describeValue, holidaysOn, inAudience, isSessionId, itemKey, localTime, locationKey, nextOccurrence, nextTimeOfDay, occurrenceAt, parseInstant, planItemChange, planVariableChange, readCalendar, rollPlain, seasonOf, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
12
+ //#region ../dsh-roleplay-model/src/plot.ts
13
+ const PLOT_STATUSES = [
14
+ "dormant",
15
+ "available",
16
+ "engaged",
17
+ "cooling",
18
+ "resolved",
19
+ "abandoned"
20
+ ];
21
+ const PLOT_NUDGE_MODES = [
22
+ "opportunity",
23
+ "reminder",
24
+ "character",
25
+ "consequence",
26
+ "escalation",
27
+ "breathing_room"
28
+ ];
29
+ //#endregion
11
30
  //#region ../dsh-roleplay-model/src/messages-zh.ts
12
31
  /** The Chinese of the texts built in code, by the English that stands in the code. A `{name}` is filled in and must stand in both. */
13
32
  const ZH = {
@@ -75,6 +94,7 @@ const ZH = {
75
94
  "Places: ": "地点:",
76
95
  "Routes: ": "路径:",
77
96
  "Things: ": "物品:",
97
+ "Background you know, to read with recall_my_lore when it bears on the moment: ": "你所知的背景(与当下相关时用 recall_my_lore 查阅):",
78
98
  "Your day and what you are after (plans, not orders: keep them, put them off or drop them as the moment and your character suggest):": "你的日程与你想达成的事(只是计划,不是命令:依当下情形和你的性格,可以照做、推迟或放弃):",
79
99
  "Your day, now: {activity}{place}, until {until}{note}.": "你此刻的日程:{activity}{place},持续到{until}{note}。",
80
100
  "Your day, next: {activity}{place}, from {from}.": "你接下来的日程:{activity}{place},{from}开始。",
@@ -221,10 +241,10 @@ const ZH = {
221
241
  //#endregion
222
242
  //#region ../dsh-roleplay-model/src/messages.ts
223
243
  /** The language a setting such as `zh-CN` or `en` stands for; English when it is none that is known. */
224
- function languageOf(code) {
244
+ function languageOf$1(code) {
225
245
  return (code ?? "").trim().toLowerCase().startsWith("zh") ? "zh" : "en";
226
246
  }
227
- const fill = (template, values) => values === void 0 ? template : template.replace(/\{(\w+)\}/g, (whole, name) => name in values ? String(values[name]) : whole);
247
+ const fill$1 = (template, values) => values === void 0 ? template : template.replace(/\{(\w+)\}/g, (whole, name) => name in values ? String(values[name]) : whole);
228
248
  const CATALOGUES = { zh: ZH };
229
249
  /**
230
250
  * The texts the engine builds for a model (briefs, reports, refusals) in a language. The text written in the code is the English one and the key of
@@ -232,7 +252,625 @@ const CATALOGUES = { zh: ZH };
232
252
  */
233
253
  function translator(language) {
234
254
  const catalogue = language === "en" ? void 0 : CATALOGUES[language];
235
- return (text, values) => fill(catalogue?.[text] ?? text, values);
255
+ return (text, values) => fill$1(catalogue?.[text] ?? text, values);
256
+ }
257
+ //#endregion
258
+ //#region src/host/sessions/errors.ts
259
+ var WorldNotFoundError = class extends Error {};
260
+ /** The world cannot be played as it is; `problems` say what to fix. */
261
+ var InvalidWorldError = class extends Error {
262
+ problems;
263
+ constructor(message, problems) {
264
+ super(message);
265
+ this.problems = problems;
266
+ }
267
+ };
268
+ /** The request cannot be honoured for this world, such as a character that cannot be played. */
269
+ var InvalidStartError = class extends Error {};
270
+ var SessionNotFoundError = class extends Error {};
271
+ /** DSH's session services are not available, so no chat can be created or retired. */
272
+ var AgentUnavailableError = class extends Error {};
273
+ /** The session is put away and cannot be played until it is brought back. */
274
+ var SessionArchivedError = class extends Error {};
275
+ /** A reflection cannot be started now: a turn is being played, or one is already running. */
276
+ var ReflectionRefusedError = class extends Error {};
277
+ //#endregion
278
+ //#region src/host/prompts/library.ts
279
+ const PROMPTS_FOLDER = "prompts";
280
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
281
+ const ID = /^[a-z0-9-]+(\/[a-z0-9-]+)*$/;
282
+ const LANGUAGE_FOLDER = /^[a-z]{2,8}$/;
283
+ const LANGUAGE = LANGUAGE_FOLDER;
284
+ const VARIABLE = /\$\{([A-Za-z]+)\}/g;
285
+ /** The folder of the prompts that ship with the package, found from this module so that it works from source and from the build. */
286
+ function shippedPromptsDirectory(from = dirname(fileURLToPath(import.meta.url))) {
287
+ for (let directory = from;; directory = dirname(directory)) {
288
+ const candidate = join(directory, PROMPTS_FOLDER);
289
+ if (existsSync(join(directory, "package.json")) && existsSync(candidate)) return candidate;
290
+ if (dirname(directory) === directory) throw new Error("the prompts shipped with the package were not found");
291
+ }
292
+ }
293
+ /** `zh-CN` and `ZH` are both `zh`; anything that is not a language tag is refused. */
294
+ function languageOf(tag) {
295
+ const primary = (tag ?? "en").trim().toLowerCase().split(/[-_]/)[0] ?? "";
296
+ if (!LANGUAGE.test(primary)) throw new Error(`"${tag}" is not a language`);
297
+ return primary;
298
+ }
299
+ /** How a language is named inside a prompt, for the instruction to write in it. */
300
+ const LANGUAGE_NAMES$1 = {
301
+ en: "English",
302
+ zh: "中文"
303
+ };
304
+ function fill(id, text, given, tag) {
305
+ const variables = {
306
+ language: LANGUAGE_NAMES$1[tag] ?? tag,
307
+ ...given
308
+ };
309
+ return text.trim().replace(/^\$\{([A-Za-z]+)\}[ \t]*(\r?\n|$)/gm, (match, name) => variables[name] === "" ? "" : match).replace(VARIABLE, (_match, name) => {
310
+ const value = variables[name];
311
+ if (value === void 0) throw new Error(`prompt ${id} uses \${${name}}, which is not given a value (given: ${Object.keys(variables).join(", ") || "none"})`);
312
+ return String(value);
313
+ });
314
+ }
315
+ /** A prompt as the package ships it, without a roleplay root: for code that has none, such as tests. */
316
+ function shippedText(id, language = "en", variables = {}) {
317
+ return fill(id, readFileSync(join(shippedPromptsDirectory(), language, `${id}.md`), "utf8"), variables, language);
318
+ }
319
+ function listFiles(directory, prefix = "") {
320
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
321
+ const name = `${prefix}${entry.name}`;
322
+ if (entry.isDirectory()) return listFiles(join(directory, entry.name), `${name}/`);
323
+ return entry.name.endsWith(".md") ? [name.slice(0, -3)] : [];
324
+ });
325
+ }
326
+ /**
327
+ * Every instruction the models are given is a file under `<root>/prompts/<language>/`, so that the person can edit them. The files
328
+ * come from the package: one that is not there (never written, or deleted to restore it) is copied again when it is needed.
329
+ */
330
+ var PromptLibrary = class extends Service {
331
+ root;
332
+ shipped;
333
+ constructor(ctx, root, shipped = shippedPromptsDirectory()) {
334
+ super(ctx, "roleplayPrompts");
335
+ this.root = root;
336
+ this.shipped = shipped;
337
+ }
338
+ get directory() {
339
+ return join(this.root.path, PROMPTS_FOLDER);
340
+ }
341
+ /** The languages the package ships prompts in. */
342
+ get languages() {
343
+ return readdirSync(this.shipped, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
344
+ }
345
+ /** Writes every shipped prompt that is missing, so that they can be found and edited before they are first used. */
346
+ bootstrap() {
347
+ for (const language of this.languages) for (const id of listFiles(join(this.shipped, language))) this.file(id, language);
348
+ }
349
+ /**
350
+ * What is wrong with the files in the root that the person edited, each with its path: empty, using a variable the prompt is not given, or holding `{{...}}`, which
351
+ * DSH's prompt assembly reads as a variable of its own. A file of an id the package does not ship is not read by anything and is left alone.
352
+ */
353
+ problems() {
354
+ if (!existsSync(this.directory)) return [];
355
+ return readdirSync(this.directory, { withFileTypes: true }).filter((entry) => entry.isDirectory() && LANGUAGE.test(entry.name)).flatMap((entry) => listFiles(join(this.directory, entry.name)).flatMap((id) => {
356
+ const path = join(this.directory, entry.name, `${id}.md`);
357
+ const text = readFileSync(path, "utf8");
358
+ const message = !ID.test(id) || ![entry.name, "en"].some((name) => existsSync(join(this.shipped, name, `${id}.md`))) ? void 0 : text.includes("{{") ? "holds \"{{\", which DSH reads as a variable of its own" : promptProblem(entry.name, id, text, this.shipped);
359
+ return message === void 0 ? [] : [{
360
+ path,
361
+ message
362
+ }];
363
+ }));
364
+ }
365
+ /**
366
+ * The prompt `id` in the language (the primary subtag of a language tag), with `${name}` replaced by the variables.
367
+ * A session may carry a file of its own under `prompts/<language>/` in its folder, which is used instead of the one in the root.
368
+ */
369
+ text(id, language, variables = {}, session) {
370
+ if (!ID.test(id)) throw new Error(`"${id}" is not a prompt id`);
371
+ const tag = languageOf(language);
372
+ const own = session === void 0 ? void 0 : this.override(id, tag, session);
373
+ return fill(id, readFileSync(own ?? this.file(id, tag), "utf8"), variables, tag);
374
+ }
375
+ override(id, language, session) {
376
+ if (!SESSION_ID.test(session)) throw new Error(`"${session}" is not a session id`);
377
+ const found = join(this.root.path, "sessions", session, PROMPTS_FOLDER, language, `${id}.md`);
378
+ return this.usable(found, id) ? found : void 0;
379
+ }
380
+ /** The path of the prompt in the root, copied from the package first when it is not there. A language the package has no prompt in uses the English one. */
381
+ file(id, language) {
382
+ const found = join(this.directory, language, `${id}.md`);
383
+ if (this.usable(found, id)) return found;
384
+ const source = [language, "en"].map((name) => join(this.shipped, name, `${id}.md`)).find((path) => existsSync(path));
385
+ if (source === void 0) throw new Error(`there is no prompt ${id} in ${language} or en`);
386
+ const target = source.startsWith(join(this.shipped, language)) ? found : join(this.directory, "en", `${id}.md`);
387
+ if (!this.usable(target, id)) {
388
+ mkdirSync(dirname(target), { recursive: true });
389
+ copyFileSync(source, target);
390
+ }
391
+ return target;
392
+ }
393
+ usable(path, id) {
394
+ if (!existsSync(path)) return false;
395
+ if (statSync(path).size === 0 || readFileSync(path, "utf8").trim() === "") throw new Error(`the prompt file ${path} (${id}) is empty; delete it to restore the original`);
396
+ return true;
397
+ }
398
+ };
399
+ const names = (text) => new Set([...text.matchAll(VARIABLE)].map((match) => match[1]));
400
+ /** Why a text cannot be the prompt `id` in the language, or nothing when it can: it must be a prompt the package has, not empty, and use only the variables the prompt is given. */
401
+ function promptProblem(language, id, text, shipped = shippedPromptsDirectory()) {
402
+ const original = ID.test(id) ? [language, "en"].map((name) => join(shipped, name, `${id}.md`)).find((path) => existsSync(path)) : void 0;
403
+ if (original === void 0) return `there is no prompt "${id}"`;
404
+ if (text.trim() === "") return "the prompt is empty";
405
+ const allowed = names(readFileSync(original, "utf8"));
406
+ const unknown = [...names(text)].filter((name) => !allowed.has(name));
407
+ return unknown.length === 0 ? void 0 : `uses ${unknown.map((name) => `\${${name}}`).join(", ")}, which the prompt is not given (it is given: ${[...allowed].join(", ") || "none"})`;
408
+ }
409
+ /**
410
+ * Copies the prompts a world carries (`prompts/<language>/<id>.md`) into a session folder, where they take the place of the ones in the root.
411
+ * Each must be a prompt the package has, in a language it ships, not empty, and may use only the variables that prompt is given.
412
+ * @returns the problems found, each with the file; nothing is copied when there are any.
413
+ */
414
+ function copyWorldPrompts(worldDirectory, target, shipped = shippedPromptsDirectory()) {
415
+ const source = join(worldDirectory, PROMPTS_FOLDER);
416
+ if (!existsSync(source)) return [];
417
+ const problems = [];
418
+ const found = [];
419
+ for (const entry of readdirSync(source, { withFileTypes: true })) {
420
+ const folder = join(source, entry.name);
421
+ if (!entry.isDirectory() || !LANGUAGE.test(entry.name)) {
422
+ problems.push({
423
+ path: folder,
424
+ message: "prompts are kept in a folder named by the language, such as en or zh"
425
+ });
426
+ continue;
427
+ }
428
+ for (const id of listFiles(folder)) {
429
+ const from = join(folder, `${id}.md`);
430
+ const message = promptProblem(entry.name, id, readFileSync(from, "utf8"), shipped);
431
+ if (message !== void 0) {
432
+ problems.push({
433
+ path: from,
434
+ message
435
+ });
436
+ continue;
437
+ }
438
+ found.push({
439
+ from,
440
+ to: join(target, PROMPTS_FOLDER, entry.name, `${id}.md`)
441
+ });
442
+ }
443
+ }
444
+ if (problems.length > 0) return problems;
445
+ for (const { from, to } of found) {
446
+ mkdirSync(dirname(to), { recursive: true });
447
+ copyFileSync(from, to);
448
+ }
449
+ return [];
450
+ }
451
+ /** A branch plays with the prompts of the session it was cut from. */
452
+ function inheritPrompts(from, to) {
453
+ if (existsSync(join(from, "prompts"))) cpSync(join(from, PROMPTS_FOLDER), join(to, PROMPTS_FOLDER), { recursive: true });
454
+ }
455
+ /** The languages the package ships prompts in. */
456
+ function shippedLanguages(shipped = shippedPromptsDirectory()) {
457
+ return readdirSync(shipped, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
458
+ }
459
+ //#endregion
460
+ //#region src/host/errors.ts
461
+ function errorMessage(error) {
462
+ return error instanceof Error ? error.message : String(error);
463
+ }
464
+ //#endregion
465
+ //#region src/host/validation.ts
466
+ function formatIssue({ path, message }) {
467
+ return path === "" ? message : `${path}: ${message}`;
468
+ }
469
+ function isRecord(value) {
470
+ return typeof value === "object" && value !== null && !Array.isArray(value);
471
+ }
472
+ /**
473
+ * Reads a JSON object field by field. Problems are collected with their path
474
+ * instead of stopping at the first one, so an author sees everything wrong in
475
+ * a file at once. A missing field, `null` and a blank string all mean "absent".
476
+ */
477
+ var Reader = class Reader {
478
+ data;
479
+ path;
480
+ issues;
481
+ constructor(data, path, issues) {
482
+ this.data = data;
483
+ this.path = path;
484
+ this.issues = issues;
485
+ }
486
+ /** Parse JSON text whose top level must be an object; reports why when it is not. */
487
+ static fromJson(text, issues) {
488
+ let data;
489
+ try {
490
+ data = JSON.parse(text.replace(/^/, ""));
491
+ } catch (error) {
492
+ issues.push({
493
+ path: "",
494
+ message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
495
+ });
496
+ return;
497
+ }
498
+ if (!isRecord(data)) {
499
+ issues.push({
500
+ path: "",
501
+ message: "expected a JSON object"
502
+ });
503
+ return;
504
+ }
505
+ return new Reader(data, "", issues);
506
+ }
507
+ fail(key, message) {
508
+ this.issues.push({
509
+ path: this.child(key),
510
+ message
511
+ });
512
+ }
513
+ /** The value as written, with `null` read as absent. */
514
+ raw(key) {
515
+ const value = this.data[key];
516
+ return value === null ? void 0 : value;
517
+ }
518
+ string(key, options = {}) {
519
+ const value = this.raw(key);
520
+ if (value !== void 0 && typeof value !== "string") {
521
+ this.fail(key, "must be a string");
522
+ return;
523
+ }
524
+ const text = value?.trim();
525
+ if (text === void 0 || text === "") {
526
+ if (options.required === true) this.fail(key, "is required");
527
+ return;
528
+ }
529
+ return text;
530
+ }
531
+ /** A string that is empty when absent. */
532
+ text(key) {
533
+ return this.string(key) ?? "";
534
+ }
535
+ number(key, range = {}) {
536
+ const value = this.raw(key);
537
+ if (value === void 0) return void 0;
538
+ if (typeof value !== "number" || !Number.isFinite(value)) {
539
+ this.fail(key, "must be a number");
540
+ return;
541
+ }
542
+ if (range.min !== void 0 && value < range.min || range.max !== void 0 && value > range.max) {
543
+ this.fail(key, `must be between ${range.min ?? "-∞"} and ${range.max ?? "∞"}`);
544
+ return;
545
+ }
546
+ return value;
547
+ }
548
+ oneOf(key, allowed, fallback) {
549
+ const value = this.string(key);
550
+ if (value === void 0) return fallback;
551
+ const match = allowed.find((candidate) => candidate === value);
552
+ if (match === void 0) {
553
+ this.fail(key, `must be one of: ${allowed.join(", ")}`);
554
+ return fallback;
555
+ }
556
+ return match;
557
+ }
558
+ /** An array of strings, trimmed, without blanks or repeats. */
559
+ strings(key) {
560
+ const value = this.raw(key);
561
+ if (value === void 0) return [];
562
+ if (!Array.isArray(value)) {
563
+ this.fail(key, "must be an array of strings");
564
+ return [];
565
+ }
566
+ const result = /* @__PURE__ */ new Set();
567
+ value.forEach((entry, index) => {
568
+ if (typeof entry !== "string") this.fail(`${key}[${index}]`, "must be a string");
569
+ else if (entry.trim() !== "") result.add(entry.trim());
570
+ });
571
+ return [...result];
572
+ }
573
+ object(key) {
574
+ const value = this.raw(key);
575
+ if (value === void 0) return void 0;
576
+ if (!isRecord(value)) {
577
+ this.fail(key, "must be an object");
578
+ return;
579
+ }
580
+ return new Reader(value, this.child(key), this.issues);
581
+ }
582
+ objects(key) {
583
+ const value = this.raw(key);
584
+ if (value === void 0) return [];
585
+ if (!Array.isArray(value)) {
586
+ this.fail(key, "must be an array of objects");
587
+ return [];
588
+ }
589
+ return value.flatMap((entry, index) => {
590
+ if (isRecord(entry)) return [new Reader(entry, this.child(`${key}[${index}]`), this.issues)];
591
+ this.fail(`${key}[${index}]`, "must be an object");
592
+ return [];
593
+ });
594
+ }
595
+ child(key) {
596
+ return this.path === "" ? key : key === "" ? this.path : `${this.path}.${key}`;
597
+ }
598
+ };
599
+ //#endregion
600
+ //#region src/host/read-document.ts
601
+ /** Authored documents are short; a larger file is not one. */
602
+ const MAX_DOCUMENT_BYTES = 1048576;
603
+ /**
604
+ * Read and parse one authored document. Every problem is added to `problems`
605
+ * with the file's path, and the document is skipped.
606
+ */
607
+ async function readDocument(file, parse, problems) {
608
+ if ((await stat(file)).size > MAX_DOCUMENT_BYTES) {
609
+ problems.push({
610
+ path: file,
611
+ message: "file is too large"
612
+ });
613
+ return;
614
+ }
615
+ const result = parse(await readFile(file, "utf8"));
616
+ if (result.ok) return result.value;
617
+ for (const issue of result.issues) problems.push({
618
+ path: file,
619
+ message: formatIssue(issue)
620
+ });
621
+ }
622
+ //#endregion
623
+ //#region src/host/plots/load.ts
624
+ const PLOTS_FILE_NAME = "plots.json";
625
+ function development(reader, fallback) {
626
+ return {
627
+ id: reader.string("id") ?? fallback,
628
+ text: reader.string("text", { required: true }) ?? "",
629
+ mode: reader.oneOf("mode", PLOT_NUDGE_MODES, "opportunity"),
630
+ prerequisites: reader.strings("prerequisites"),
631
+ guidance: reader.text("guidance"),
632
+ avoid: reader.strings("avoid")
633
+ };
634
+ }
635
+ /** Parse the optional world-level list of dramatic possibilities. */
636
+ function parsePlotsFile(text) {
637
+ const issues = [];
638
+ const wrapper = Reader.fromJson(`{"plots":${text.replace(/^/, "")}}`, issues);
639
+ if (wrapper === void 0) return {
640
+ ok: false,
641
+ issues
642
+ };
643
+ const plots = wrapper.objects("plots").map((reader, plotIndex) => {
644
+ const pacing = reader.object("pacing");
645
+ const hooks = reader.objects("hooks").map((entry, index) => development(entry, `hook-${index + 1}`));
646
+ const developments = reader.objects("developments").map((entry, index) => development(entry, `development-${index + 1}`));
647
+ return {
648
+ id: reader.string("id", { required: true }) ?? `plot-${plotIndex + 1}`,
649
+ name: reader.string("name", { required: true }) ?? "",
650
+ premise: reader.string("premise", { required: true }) ?? "",
651
+ themes: reader.strings("themes"),
652
+ hooks,
653
+ developments,
654
+ stakes: reader.strings("stakes"),
655
+ resolutions: reader.strings("resolutions"),
656
+ participants: reader.strings("participants"),
657
+ start: reader.oneOf("start", PLOT_STATUSES, "available"),
658
+ pacing: {
659
+ quietTurns: pacing?.number("quiet_turns", {
660
+ min: 1,
661
+ max: 20
662
+ }) ?? pacing?.number("quietTurns", {
663
+ min: 1,
664
+ max: 20
665
+ }) ?? 3,
666
+ cooldownTurns: pacing?.number("cooldown_turns", {
667
+ min: 1,
668
+ max: 50
669
+ }) ?? pacing?.number("cooldownTurns", {
670
+ min: 1,
671
+ max: 50
672
+ }) ?? 4,
673
+ cooldownDays: pacing?.number("cooldown_days", {
674
+ min: 0,
675
+ max: 365
676
+ }) ?? pacing?.number("cooldownDays", {
677
+ min: 0,
678
+ max: 365
679
+ }) ?? 1
680
+ }
681
+ };
682
+ });
683
+ const ids = plots.map((plot) => plot.id);
684
+ ids.forEach((id, index) => {
685
+ if (ids.indexOf(id) !== index) issues.push({
686
+ path: `plots[${index}].id`,
687
+ message: `plot id "${id}" is defined twice`
688
+ });
689
+ });
690
+ for (const [plotIndex, plot] of plots.entries()) {
691
+ const steps = [...plot.hooks, ...plot.developments];
692
+ const stepIds = steps.map((step) => step.id);
693
+ stepIds.forEach((id, index) => {
694
+ if (stepIds.indexOf(id) !== index) issues.push({
695
+ path: `plots[${plotIndex}]`,
696
+ message: `development id "${id}" is defined twice`
697
+ });
698
+ });
699
+ for (const step of steps) for (const required of step.prerequisites) if (!stepIds.includes(required)) issues.push({
700
+ path: `plots[${plotIndex}]`,
701
+ message: `development "${step.id}" requires unknown development "${required}"`
702
+ });
703
+ }
704
+ return issues.length === 0 ? {
705
+ ok: true,
706
+ value: plots
707
+ } : {
708
+ ok: false,
709
+ issues
710
+ };
711
+ }
712
+ async function loadPlots(worldDir) {
713
+ const result = {
714
+ plots: [],
715
+ problems: []
716
+ };
717
+ const file = join(worldDir, PLOTS_FILE_NAME);
718
+ try {
719
+ result.plots = await readDocument(file, parsePlotsFile, result.problems) ?? [];
720
+ } catch (error) {
721
+ if (error.code !== "ENOENT") result.problems.push({
722
+ path: file,
723
+ message: errorMessage(error)
724
+ });
725
+ }
726
+ return result;
727
+ }
728
+ function plotReferenceProblems(plots, entities) {
729
+ const known = new Set(entities);
730
+ return plots.flatMap((plot) => plot.participants.filter((participant) => !known.has(participant)).map((participant) => `plot "${plot.id}" names unknown participant "${participant}"`));
731
+ }
732
+ //#endregion
733
+ //#region src/host/translate/language.ts
734
+ const STORY_LANGUAGES = ["en", "zh"];
735
+ /** Less than this many letters of either script is too little to tell a language. */
736
+ const MIN_LETTERS = 20;
737
+ /** A text is Chinese when this share of its Han and Latin letters is Han: names in the other script do not decide it. */
738
+ const HAN_SHARE = .3;
739
+ const count = (text, pattern) => text.match(pattern)?.length ?? 0;
740
+ /** The language a text is written in, by the script of its letters; nothing when there is too little text to tell. */
741
+ function textLanguage(text) {
742
+ const han = count(text, /\p{Script=Han}/gu);
743
+ const latin = count(text, /\p{Script=Latin}/gu);
744
+ if (han + latin < MIN_LETTERS) return void 0;
745
+ return han / (han + latin) >= HAN_SHARE ? "zh" : "en";
746
+ }
747
+ const isStoryLanguage = (value) => value === "en" || value === "zh";
748
+ const LANGUAGE_NAMES = {
749
+ en: {
750
+ en: "English",
751
+ zh: "英文"
752
+ },
753
+ zh: {
754
+ en: "Chinese",
755
+ zh: "中文"
756
+ }
757
+ };
758
+ const FOREIGN_WORD = /(?<![\p{L}\p{N}_-])\p{Ll}[\p{Ll}'’]{2,}(?![\p{L}\p{N}_-])/gu;
759
+ const LATIN_WORD = /^\p{Script=Latin}+(?:['’]\p{Script=Latin}+)?$/u;
760
+ /**
761
+ * Ordinary English words left in a Chinese text. Names and acronyms keep their capitals and are left alone, so only lowercase words count;
762
+ * the script test above cannot see them because Han letters outnumber them.
763
+ */
764
+ function strayWords(text) {
765
+ if (!/\p{Script=Han}/u.test(text)) return [];
766
+ return [...new Set((text.match(FOREIGN_WORD) ?? []).filter((word) => LATIN_WORD.test(word)))];
767
+ }
768
+ /** What is wrong with texts that should be in the chat's language but are written in the other one; nothing when they are right, too short to tell, or the language is not one we can read. */
769
+ function wrongLanguage(wanted, texts, options = {}) {
770
+ if (!isStoryLanguage(wanted)) return void 0;
771
+ const wrong = Object.entries(texts).flatMap(([name, text]) => {
772
+ const found = text === void 0 ? void 0 : textLanguage(text);
773
+ if (found !== void 0 && found !== wanted) return [`${name} is written in ${LANGUAGE_NAMES[found].en}`];
774
+ const strays = options.strays === true && wanted === "zh" && text !== void 0 ? strayWords(text).slice(0, 4) : [];
775
+ return strays.length === 0 ? [] : [`${name} leaves English words in (${strays.map((word) => `"${word}"`).join(", ")})`];
776
+ });
777
+ return wrong.length === 0 ? void 0 : `${wrong.join(" and ")}: write it in ${LANGUAGE_NAMES[wanted].en} (${LANGUAGE_NAMES[wanted][wanted]})`;
778
+ }
779
+ //#endregion
780
+ //#region src/host/pacing/director.ts
781
+ const PLOTS_METADATA_KEY = "roleplay.pacing.plots";
782
+ function populatePlots(metadata, plots) {
783
+ const progress = plots.map((plot) => ({
784
+ plot,
785
+ status: plot.start,
786
+ introduced: [],
787
+ rejected: [],
788
+ lastNudgeTurn: 0
789
+ }));
790
+ metadata.setValue(PLOTS_METADATA_KEY, progress);
791
+ }
792
+ function addSessionPlot(store, plot) {
793
+ const plots = progressOf(store);
794
+ if (plots.some((entry) => entry.plot.id === plot.id)) throw new Error(`there is already a plot "${plot.id}"`);
795
+ plots.push({
796
+ plot,
797
+ status: plot.start,
798
+ introduced: [],
799
+ rejected: [],
800
+ lastNudgeTurn: 0
801
+ });
802
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
803
+ }
804
+ function plotAuthorNeeded(store, turn) {
805
+ if (progressOf(store).length > 0 || turn < 5) return false;
806
+ return store.story.events.list({
807
+ fromTurn: Math.max(1, turn - 2),
808
+ toTurn: turn - 1
809
+ }).length === 0 && store.story.threads.list("open").length === 0;
810
+ }
811
+ function plotProgressOf(metadata) {
812
+ const value = metadata.getValue(PLOTS_METADATA_KEY);
813
+ return Array.isArray(value) ? value : [];
814
+ }
815
+ function progressOf(store) {
816
+ return plotProgressOf(store.story.metadata);
817
+ }
818
+ /** Select one uncommitted possibility when the story has genuinely gone quiet; selection never makes it happen. */
819
+ function pacingAdvice(store, turn) {
820
+ const plots = progressOf(store);
821
+ if (plots.length === 0) return void 0;
822
+ const now = store.story.clock.get()?.now;
823
+ const recent = store.story.events.list({
824
+ fromTurn: Math.max(1, turn - 2),
825
+ toTurn: turn - 1
826
+ });
827
+ const openThreads = store.story.threads.list("open");
828
+ for (const progress of plots) {
829
+ if (![
830
+ "available",
831
+ "engaged",
832
+ "cooling"
833
+ ].includes(progress.status)) continue;
834
+ const quietTurns = progress.plot.pacing.quietTurns + (openThreads.length === 0 ? 0 : 2);
835
+ if (recent.length > 0 || turn <= quietTurns) continue;
836
+ if (turn - progress.lastNudgeTurn < progress.plot.pacing.cooldownTurns) continue;
837
+ if (now !== void 0 && progress.lastNudgeAt !== void 0 && now - progress.lastNudgeAt < progress.plot.pacing.cooldownDays * 864e5) continue;
838
+ const step = [...progress.plot.hooks, ...progress.plot.developments].filter((step) => !progress.introduced.includes(step.id) && !progress.rejected.includes(step.id) && step.prerequisites.every((id) => progress.introduced.includes(id)))[0];
839
+ if (step === void 0) continue;
840
+ const quietFor = turn - progress.lastNudgeTurn;
841
+ progress.lastNudgeTurn = turn;
842
+ if (now !== void 0) progress.lastNudgeAt = now;
843
+ progress.status = progress.status === "available" ? "engaged" : progress.status;
844
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
845
+ return {
846
+ need: quietFor > progress.plot.pacing.quietTurns * 2 ? "clear" : "gentle",
847
+ reason: openThreads.length === 0 ? "no recorded development or immediate thread has guided the last few turns" : "the open threads have remained without recorded development for several turns",
848
+ plot: progress.plot.id,
849
+ plotName: progress.plot.name,
850
+ development: step.id,
851
+ mode: step.mode,
852
+ guidance: step.guidance || step.text,
853
+ avoid: step.avoid
854
+ };
855
+ }
856
+ }
857
+ function describePacingAdvice(advice) {
858
+ return `Pacing opportunity (${advice.need}; advice only, not an event): ${advice.plotName} [plot ${advice.plot}] / development ${advice.development}\nWhy now: ${advice.reason}.\nPossible nudge (${advice.mode}): ${advice.guidance}${advice.avoid.length === 0 ? "" : `\nDo not: ${advice.avoid.join("; ")}.`}\nUse it only if it fits the present scene. Do not make the player accept it, do not make a character act without activate_characters, and do not mark the development complete merely because it was offered.`;
859
+ }
860
+ function updatePlotProgress(store, plotId, developmentId, action) {
861
+ const plots = progressOf(store);
862
+ const progress = plots.find((entry) => entry.plot.id === plotId);
863
+ if (progress === void 0) throw new Error(`there is no plot "${plotId}"`);
864
+ if (action === "resolved" || action === "abandoned") progress.status = action;
865
+ else {
866
+ if (developmentId === void 0) throw new Error(`${action} needs a development`);
867
+ if (![...progress.plot.hooks, ...progress.plot.developments].some((step) => step.id === developmentId)) throw new Error(`plot "${plotId}" has no development "${developmentId}"`);
868
+ const target = action === "introduced" ? progress.introduced : progress.rejected;
869
+ if (!target.includes(developmentId)) target.push(developmentId);
870
+ if (action === "introduced") progress.status = "engaged";
871
+ }
872
+ store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
873
+ return progress;
236
874
  }
237
875
  //#endregion
238
876
  //#region src/host/orchestration/protocol.ts
@@ -563,7 +1201,7 @@ const NOTE_KINDS = [
563
1201
  ];
564
1202
  //#endregion
565
1203
  //#region src/host/sessions/notes.ts
566
- const KEY$3 = "notes";
1204
+ const KEY$4 = "notes";
567
1205
  const isNote = (value) => {
568
1206
  if (typeof value !== "object" || value === null) return false;
569
1207
  const note = value;
@@ -571,12 +1209,12 @@ const isNote = (value) => {
571
1209
  };
572
1210
  /** The notes of a session, at most one per kind. */
573
1211
  function readNotes(session) {
574
- const stored = session.metadata.getValue(KEY$3);
1212
+ const stored = session.metadata.getValue(KEY$4);
575
1213
  return Array.isArray(stored) ? stored.filter(isNote) : [];
576
1214
  }
577
1215
  /** Replaces the note of the same kind. */
578
1216
  function putNote(session, note) {
579
- session.metadata.setValue(KEY$3, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1217
+ session.metadata.setValue(KEY$4, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
580
1218
  }
581
1219
  /** The most lines one note keeps: what is past it is not told. */
582
1220
  const MAX_NOTE_LINES = 8;
@@ -591,7 +1229,7 @@ function addToNote(session, kind, turn, lines) {
591
1229
  }
592
1230
  /** Removes every note: they belong to the turn that made them. */
593
1231
  function clearNotes(session) {
594
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$3, []);
1232
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$4, []);
595
1233
  }
596
1234
  /**
597
1235
  * The notes of a session, for the player's screen.
@@ -609,6 +1247,970 @@ function notesOfSession(deps, id) {
609
1247
  }];
610
1248
  }
611
1249
  //#endregion
1250
+ //#region src/host/triggers/deliver.ts
1251
+ const KEY$3 = "triggers.withdrawn";
1252
+ /** Why a note was withdrawn instead of told, by the number of the note. */
1253
+ function readWithdrawn(session) {
1254
+ const stored = session.metadata.getValue(KEY$3);
1255
+ if (!Array.isArray(stored)) return {};
1256
+ return Object.fromEntries(stored.flatMap((entry) => {
1257
+ const { note, reason } = entry ?? {};
1258
+ return typeof note === "number" && typeof reason === "string" ? [[note, reason]] : [];
1259
+ }));
1260
+ }
1261
+ /**
1262
+ * Tells these notes as the story stands now: each is written from the story at this moment, and one that no longer applies is let go and the
1263
+ * reason kept (`readWithdrawn`). @returns what is to be told, with the number of its note.
1264
+ */
1265
+ function deliverNow(session, notes, clock) {
1266
+ const { shown, withdrawn } = session.deliverNotes(notes, clock);
1267
+ if (withdrawn.length > 0) session.transaction(() => {
1268
+ for (const { note } of withdrawn) session.triggers.resolveNote(note.id, "lapsed");
1269
+ const before = Object.entries(readWithdrawn(session)).map(([note, reason]) => ({
1270
+ note: Number(note),
1271
+ reason
1272
+ }));
1273
+ session.metadata.setValue(KEY$3, [...before, ...withdrawn.map(({ note, reason }) => ({
1274
+ note: note.id,
1275
+ reason
1276
+ }))].slice(-100));
1277
+ });
1278
+ return shown.map(({ note, text }) => ({
1279
+ id: note.id,
1280
+ text
1281
+ }));
1282
+ }
1283
+ //#endregion
1284
+ //#region src/host/triggers/judged.ts
1285
+ const KEY$2 = "triggers.judged";
1286
+ function readVerdicts(session) {
1287
+ const stored = session.metadata.getValue(KEY$2);
1288
+ if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
1289
+ const verdicts = {};
1290
+ for (const [statement, value] of Object.entries(stored)) {
1291
+ const verdict = value;
1292
+ if (typeof verdict === "object" && verdict !== null && typeof verdict.holds === "boolean" && typeof verdict.turn === "number") verdicts[statement] = {
1293
+ holds: verdict.holds,
1294
+ turn: verdict.turn
1295
+ };
1296
+ }
1297
+ return verdicts;
1298
+ }
1299
+ /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
1300
+ function writeVerdicts(session, verdicts, keep) {
1301
+ session.metadata.setValue(KEY$2, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1302
+ }
1303
+ /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
1304
+ const verdictReader = (session) => {
1305
+ const verdicts = readVerdicts(session);
1306
+ return (statement) => verdicts[statement]?.holds === true;
1307
+ };
1308
+ //#endregion
1309
+ //#region src/host/triggers/notes.ts
1310
+ /** Fires the triggers whose conditions just came true, and says what each did in words. A trigger that could not be applied is reported and given up. */
1311
+ function fireTriggers(session, input) {
1312
+ const { settings, turn, round, now, zone, problem } = input;
1313
+ if (!settings.triggers.enabled) return { fired: [] };
1314
+ const before = Math.max(0, ...session.triggers.notes().map((note) => note.id));
1315
+ const run = session.runTriggers({
1316
+ turn,
1317
+ round,
1318
+ now,
1319
+ zone,
1320
+ maxFires: settings.triggers.maxFires,
1321
+ judged: verdictReader(session)
1322
+ });
1323
+ for (const failure of run.failed) problem(`the trigger "${failure.trigger.key}" could not fire and is given up: ${failure.problem}`);
1324
+ const names = new Map(session.characters.list().map((character) => [character.id, character.name]));
1325
+ const fresh = session.triggers.notes({ status: "pending" }).filter((note) => note.id > before);
1326
+ const told = new Map(deliverNow(session, fresh, {
1327
+ now,
1328
+ zone
1329
+ }).map((entry) => [entry.id, entry.text]));
1330
+ return { fired: run.fired.map((fired) => ({
1331
+ name: fired.trigger.name,
1332
+ events: fired.events,
1333
+ cues: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "cue" && told.has(note.id)).map((note) => ({
1334
+ names: note.characterIds.flatMap((id) => names.get(id) ?? []),
1335
+ text: told.get(note.id)
1336
+ })),
1337
+ beats: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "beat" && told.has(note.id)).map((note) => ({
1338
+ id: note.id,
1339
+ text: told.get(note.id)
1340
+ }))
1341
+ })) };
1342
+ }
1343
+ /** When something is to happen, as it is told: the date and how far off it is. */
1344
+ function whenText(at, clock) {
1345
+ if (at === void 0) return void 0;
1346
+ return `${describeInstant(at, clock.zone)}${at > clock.now ? `, in ${describeDuration(at - clock.now)}` : ""}`;
1347
+ }
1348
+ function whoKnows(session, announcement) {
1349
+ const { audience } = announcement;
1350
+ if (audience === "everyone") return "everyone";
1351
+ if ("place" in audience) return `whoever is at ${session.locations.list().find((place) => locationKey(place) === audience.place)?.name ?? audience.place}`;
1352
+ return audience.characters.map((key) => session.characters.list().find((entry) => (entry.sourceId ?? String(entry.id)) === key)?.name ?? key).join(", ");
1353
+ }
1354
+ /** At most this many announcements are told to one character at once: soonest first. */
1355
+ const MAX_UPCOMING_FOR_CHARACTER = 3;
1356
+ /** The beats still to weave in, the cues of a character, and what is done with them. Each is written from the story as it stands when it is told, and one that no longer applies is withdrawn. */
1357
+ function noteStore(session, settings, clock) {
1358
+ return {
1359
+ upcoming: (turn) => {
1360
+ const now = clock(turn);
1361
+ return announcements(session, now).map((entry) => {
1362
+ const when = whenText(entry.at, now);
1363
+ return {
1364
+ text: entry.text,
1365
+ who: whoKnows(session, entry),
1366
+ ...when === void 0 ? {} : { when }
1367
+ };
1368
+ });
1369
+ },
1370
+ upcomingFor: (characterId, turn) => {
1371
+ const now = clock(turn);
1372
+ return announcements(session, now).filter((entry) => inAudience(session, entry.audience, characterId)).slice(0, MAX_UPCOMING_FOR_CHARACTER).map((entry) => {
1373
+ const when = whenText(entry.at, now);
1374
+ return {
1375
+ text: entry.text,
1376
+ ...when === void 0 ? {} : { when }
1377
+ };
1378
+ });
1379
+ },
1380
+ pendingBeats: () => deliverNow(session, session.triggers.notes({
1381
+ status: "pending",
1382
+ kind: "beat"
1383
+ }), clock(session.metadata.get().turns + 1)),
1384
+ resolveBeats: (ids) => {
1385
+ const pending = new Set(session.triggers.notes({
1386
+ status: "pending",
1387
+ kind: "beat"
1388
+ }).map((note) => note.id));
1389
+ const unknown = ids.filter((id) => !pending.has(id));
1390
+ if (unknown.length > 0) throw new Error(`${unknown.join(", ")} ${unknown.length === 1 ? "is" : "are"} not ${unknown.length === 1 ? "a beat" : "beats"} still to weave in`);
1391
+ session.transaction(() => {
1392
+ for (const id of ids) session.triggers.resolveNote(id, "done");
1393
+ });
1394
+ },
1395
+ cuesFor: (characterId) => deliverNow(session, session.triggers.notes({
1396
+ status: "pending",
1397
+ kind: "cue"
1398
+ }).filter((note) => note.characterIds.includes(characterId)), clock(session.metadata.get().turns + 1)),
1399
+ doneCues: (ids) => {
1400
+ session.transaction(() => {
1401
+ for (const id of ids) session.triggers.resolveNote(id, "done");
1402
+ });
1403
+ },
1404
+ lapseNotes: (turn) => {
1405
+ const { triggers } = settings();
1406
+ session.lapseNotes(turn, {
1407
+ beats: triggers.beatTurns,
1408
+ cues: triggers.cueTurns
1409
+ });
1410
+ }
1411
+ };
1412
+ }
1413
+ //#endregion
1414
+ //#region src/host/sessions/activity.ts
1415
+ const KEY$1 = "activity";
1416
+ const isEntry = (value) => {
1417
+ if (typeof value !== "object" || value === null) return false;
1418
+ const entry = value;
1419
+ return typeof entry["at"] === "number" && typeof entry["label"] === "string" && typeof entry["model"] === "string" && typeof entry["ms"] === "number" && typeof entry["calls"] === "number" && (entry["error"] === void 0 || typeof entry["error"] === "string");
1420
+ };
1421
+ /** The recorded runs, oldest first. */
1422
+ function readActivity(session) {
1423
+ const stored = session.metadata.getValue(KEY$1);
1424
+ return Array.isArray(stored) ? stored.filter(isEntry) : [];
1425
+ }
1426
+ /** Files the run and returns the runs that fell off the end of the record to make room. */
1427
+ function recordActivity(session, entry) {
1428
+ const all = [...readActivity(session), entry];
1429
+ session.metadata.setValue(KEY$1, all.slice(-60));
1430
+ return all.slice(0, -60);
1431
+ }
1432
+ const RUN_FOLDER = "activity";
1433
+ const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1434
+ const runFile = (folder, run) => {
1435
+ if (!RUN_ID.test(run)) throw new RangeError(`"${run}" is not a run`);
1436
+ return join(folder, RUN_FOLDER, `${run}.json`);
1437
+ };
1438
+ /** Stores what a helper was told and did, beside the session's database: it is bulky, and only read to find out what went wrong. */
1439
+ function keepRunDetail(folder, run, detail) {
1440
+ const file = runFile(folder, run);
1441
+ mkdirSync(join(folder, RUN_FOLDER), { recursive: true });
1442
+ writeFileSync(`${file}.tmp`, JSON.stringify(detail));
1443
+ renameSync(`${file}.tmp`, file);
1444
+ }
1445
+ /** The stored detail of a run, or nothing when it was not kept or has been dropped. */
1446
+ function readRunDetail(folder, run) {
1447
+ try {
1448
+ return JSON.parse(readFileSync(runFile(folder, run), "utf8"));
1449
+ } catch (error) {
1450
+ if (error.code === "ENOENT") return void 0;
1451
+ throw error;
1452
+ }
1453
+ }
1454
+ function forgetRunDetails(folder, dropped) {
1455
+ for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
1456
+ }
1457
+ //#endregion
1458
+ //#region src/host/sessions/usage.ts
1459
+ const KEY = "usage";
1460
+ const isCount = (value) => typeof value === "object" && value !== null && [
1461
+ "input",
1462
+ "cached",
1463
+ "output"
1464
+ ].every((field) => typeof value[field] === "number");
1465
+ const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
1466
+ /** What each turn used, oldest first. The record belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1467
+ function readUsage(session) {
1468
+ const stored = session.metadata.getValue(KEY);
1469
+ return Array.isArray(stored) ? stored.filter(isUsage) : [];
1470
+ }
1471
+ /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
1472
+ function addUsage(session, turn, who, tokens) {
1473
+ const all = readUsage(session);
1474
+ const at = all.findIndex((entry) => entry.turn === turn);
1475
+ const entry = at === -1 ? {
1476
+ turn,
1477
+ master: NO_TOKENS,
1478
+ helpers: NO_TOKENS,
1479
+ runs: 0
1480
+ } : all[at];
1481
+ const next = who === "master" ? {
1482
+ ...entry,
1483
+ master: addTokens(entry.master, tokens)
1484
+ } : {
1485
+ ...entry,
1486
+ helpers: addTokens(entry.helpers, tokens),
1487
+ runs: entry.runs + 1
1488
+ };
1489
+ if (at === -1) all.push(next);
1490
+ else all[at] = next;
1491
+ all.sort((a, b) => a.turn - b.turn);
1492
+ session.metadata.setValue(KEY, all);
1493
+ }
1494
+ //#endregion
1495
+ //#region src/host/clock/agenda.ts
1496
+ const CURSOR = "agenda.cursor";
1497
+ const ASKED = "agenda.asked";
1498
+ /** Characters on their way to the place their day has them at, by character id: they get there when the way has taken as long as it takes. */
1499
+ const TRAVEL = "agenda.travel";
1500
+ /** At most this many characters are asked to be given a day at a time, so that it never floods the world author. */
1501
+ const MAX_ASKED = 3;
1502
+ /** How far ahead the characters are told about what comes next in their day. */
1503
+ const NEXT_HORIZON = 240 * MINUTE;
1504
+ /** What a character is shown of its own agenda at most. */
1505
+ const SHOWN_ENGAGEMENTS = 4;
1506
+ const SHOWN_GOALS = 3;
1507
+ const keyOfCharacter$1 = (character) => character.sourceId ?? String(character.id);
1508
+ /**
1509
+ * Bring the days of the characters up to the story's time: those who are not in the player's scene go where their
1510
+ * routine has them now, and take up what it has them doing, when the window they are in has changed since the last
1511
+ * time. Characters in the scene stay: the game master is told what their day expects of them instead. It costs
1512
+ * nothing but a look at each character's windows, however long the story was skipped.
1513
+ */
1514
+ function catchUpRoutines(session, zone, now, turn, ask) {
1515
+ return session.transaction(() => {
1516
+ const cursor = typeof session.metadata.getValue(CURSOR) === "number" ? session.metadata.getValue(CURSOR) : void 0;
1517
+ if (cursor === now) return [];
1518
+ const player = session.characters.list().find((character) => character.control === "player");
1519
+ const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1520
+ const moves = [];
1521
+ const stored = session.metadata.getValue(TRAVEL);
1522
+ const journeys = typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
1523
+ const arrive = (character, target) => {
1524
+ if (target.locationId !== void 0) {
1525
+ session.move(character.id, {
1526
+ to: target.locationId,
1527
+ ignoreExits: true,
1528
+ ...target.position === void 0 ? {} : { position: target.position },
1529
+ ...target.featureKey === void 0 ? {} : { featureKey: target.featureKey }
1530
+ });
1531
+ moves.push({
1532
+ character: keyOfCharacter$1(character),
1533
+ name: character.name,
1534
+ to: session.locations.get(target.locationId)?.name ?? String(target.locationId),
1535
+ activity: target.activity
1536
+ });
1537
+ }
1538
+ if (session.characterStates.get(character.id)?.activity !== target.activity) session.characterStates.update(character.id, { activity: target.activity });
1539
+ };
1540
+ const alreadyAsked = new Set(Array.isArray(session.metadata.getValue(ASKED)) ? session.metadata.getValue(ASKED) : []);
1541
+ const asked = [];
1542
+ for (const character of session.characters.list()) {
1543
+ if (character.control === "player") continue;
1544
+ const characterId = character.id;
1545
+ const window = session.routines.list(characterId);
1546
+ const here = session.placements.get("character", characterId);
1547
+ const away = playerPlace === void 0 || here?.locationId !== playerPlace;
1548
+ if (window.length === 0) {
1549
+ if (ask && playerPlace !== void 0 && away && cursor !== void 0 && asked.length < MAX_ASKED && character.kind === "person" && character.tier !== "background" && !alreadyAsked.has(characterId)) {
1550
+ session.consolidation.enqueue({
1551
+ kind: "character",
1552
+ subjectId: characterId,
1553
+ note: "has no routine: give it a day (routines), as far as its role and the story imply",
1554
+ turn
1555
+ });
1556
+ asked.push(characterId);
1557
+ }
1558
+ continue;
1559
+ }
1560
+ if (!away) continue;
1561
+ const current = occurrenceAt(window, now, zone);
1562
+ const journey = journeys[characterId];
1563
+ if (journey !== void 0) {
1564
+ const same = current !== void 0 && current.window.id === journey.windowId && current.startsAt === journey.startsAt;
1565
+ if (same && now < journey.arriveAt) continue;
1566
+ delete journeys[characterId];
1567
+ if (same) {
1568
+ arrive(character, current.window);
1569
+ continue;
1570
+ }
1571
+ }
1572
+ if (current === void 0) continue;
1573
+ const before = cursor === void 0 ? void 0 : occurrenceAt(window, cursor, zone);
1574
+ if (before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
1575
+ const target = current.window;
1576
+ if (target.locationId !== void 0 && (here?.locationId !== target.locationId || target.position !== void 0 && here.position !== target.position)) {
1577
+ const way = here?.locationId === target.locationId ? void 0 : session.planMove(characterId, { to: target.locationId });
1578
+ const seconds = way?.ok === true ? way.plan.travelSeconds : void 0;
1579
+ if (seconds !== void 0 && current.startsAt + seconds * 1e3 > now) {
1580
+ journeys[characterId] = {
1581
+ windowId: target.id,
1582
+ startsAt: current.startsAt,
1583
+ arriveAt: current.startsAt + seconds * 1e3
1584
+ };
1585
+ const text = `on the way to ${session.locations.get(target.locationId)?.name ?? String(target.locationId)}, for "${target.activity}"`;
1586
+ if (session.characterStates.get(characterId)?.activity !== text) session.characterStates.update(characterId, { activity: text });
1587
+ continue;
1588
+ }
1589
+ arrive(character, target);
1590
+ } else if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
1591
+ }
1592
+ session.metadata.setValue(CURSOR, now);
1593
+ session.metadata.setValue(TRAVEL, journeys);
1594
+ if (asked.length > 0) session.metadata.setValue(ASKED, [...alreadyAsked, ...asked]);
1595
+ return moves;
1596
+ });
1597
+ }
1598
+ /** A character's agenda at an instant, with places by name and others by name. */
1599
+ function agendaView(session, characterId, zone, now) {
1600
+ const agenda = agendaAt(session, characterId, now, zone, {
1601
+ horizon: NEXT_HORIZON,
1602
+ engagements: SHOWN_ENGAGEMENTS,
1603
+ goals: SHOWN_GOALS
1604
+ });
1605
+ const place = (id) => id === void 0 ? void 0 : session.locations.get(id)?.name;
1606
+ const names = (ids) => ids.filter((id) => id !== characterId).map((id) => session.characters.get(id)?.name ?? String(id));
1607
+ return {
1608
+ zone,
1609
+ ...agenda.now === void 0 ? {} : { now: {
1610
+ activity: agenda.now.window.activity,
1611
+ ...place(agenda.now.window.locationId) === void 0 ? {} : { place: place(agenda.now.window.locationId) },
1612
+ until: agenda.now.endsAt,
1613
+ interruptible: agenda.now.window.interruptible
1614
+ } },
1615
+ ...agenda.next === void 0 ? {} : { next: {
1616
+ activity: agenda.next.window.activity,
1617
+ ...place(agenda.next.window.locationId) === void 0 ? {} : { place: place(agenda.next.window.locationId) },
1618
+ at: agenda.next.startsAt
1619
+ } },
1620
+ engagements: agenda.engagements.map(({ engagement, overdue }) => ({
1621
+ title: engagement.title,
1622
+ at: engagement.at,
1623
+ ...place(engagement.locationId) === void 0 ? {} : { place: place(engagement.locationId) },
1624
+ with: names(engagement.participants),
1625
+ overdue
1626
+ })),
1627
+ goals: agenda.goals.map(({ intent, deadlineAt, overdue }) => ({
1628
+ name: intent.name,
1629
+ type: intent.type,
1630
+ description: intent.description,
1631
+ plan: intent.plan.slice(0, 3),
1632
+ ...deadlineAt === void 0 ? {} : { deadline: deadlineAt },
1633
+ overdue
1634
+ }))
1635
+ };
1636
+ }
1637
+ /** How soon ahead the game master is told of a window ending or a commitment falling due. */
1638
+ const SOON = 30 * MINUTE;
1639
+ const MAX_NOTES = 6;
1640
+ /** An engagement that has been overdue for longer than this is not worth the game master's attention every turn. */
1641
+ const STALE = 1440 * MINUTE;
1642
+ function sceneAgenda(session, zone, now, moved) {
1643
+ const player = session.characters.list().find((character) => character.control === "player");
1644
+ const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1645
+ const withPlayer = new Set(session.characters.list().filter((character) => playerPlace !== void 0 && session.placements.get("character", character.id)?.locationId === playerPlace && character.control !== "player").map((character) => character.id));
1646
+ const here = [];
1647
+ for (const characterId of withPlayer) {
1648
+ const windows = session.routines.list(characterId);
1649
+ const current = occurrenceAt(windows, now, zone);
1650
+ const upcoming = nextOccurrence(windows, now, zone, SOON);
1651
+ const name = session.characters.get(characterId)?.name ?? String(characterId);
1652
+ const place = current?.window.locationId === void 0 ? void 0 : session.locations.get(current.window.locationId);
1653
+ if (current !== void 0 && current.window.locationId !== void 0 && current.window.locationId !== playerPlace) here.push({
1654
+ name,
1655
+ note: `its day says "${current.window.activity}"${place === void 0 ? "" : ` at ${place.name}`} now, yet it is here`
1656
+ });
1657
+ else if (current !== void 0 && current.endsAt - now <= SOON) here.push({
1658
+ name,
1659
+ note: `"${current.window.activity}" is due to end soon`
1660
+ });
1661
+ else if (current === void 0 && upcoming !== void 0) here.push({
1662
+ name,
1663
+ note: `"${upcoming.window.activity}" begins soon${upcoming.window.locationId === void 0 ? "" : ` at ${session.locations.get(upcoming.window.locationId)?.name ?? ""}`}`
1664
+ });
1665
+ }
1666
+ const engagements = session.engagements.list({
1667
+ status: "pending",
1668
+ to: now + SOON
1669
+ }).filter((engagement) => now - (engagement.until ?? engagement.at) < STALE).slice(0, MAX_NOTES).map((engagement) => ({
1670
+ title: engagement.title,
1671
+ at: engagement.at,
1672
+ ...engagement.locationId === void 0 ? {} : { place: session.locations.get(engagement.locationId)?.name ?? "" },
1673
+ with: engagement.participants.map((id) => session.characters.get(id)?.name ?? String(id)),
1674
+ overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE)
1675
+ }));
1676
+ return {
1677
+ zone,
1678
+ moved,
1679
+ here: here.slice(0, MAX_NOTES),
1680
+ engagements
1681
+ };
1682
+ }
1683
+ //#endregion
1684
+ //#region src/host/clock/passage.ts
1685
+ /** The start of a turn: the time, how long the player was away, and what the days of the characters make of it. */
1686
+ function startTurn(session, config, turn, wall) {
1687
+ const started = beginTurn(session, config, turn, wall);
1688
+ const moved = catchUpRoutines(session, started.time.zone, started.time.now, turn, true);
1689
+ return {
1690
+ ...started,
1691
+ agenda: sceneAgenda(session, started.time.zone, started.time.now, moved)
1692
+ };
1693
+ }
1694
+ /** A round passes, and the characters outside the scene take up what their days have for the new time. */
1695
+ function passRound(session, config, turn, round, wall, stated, minimum) {
1696
+ const span = endRound(session, config, turn, round, wall, stated, minimum);
1697
+ return {
1698
+ ...span,
1699
+ moved: catchUpRoutines(session, span.zone, span.to, turn, false)
1700
+ };
1701
+ }
1702
+ /** Time is skipped, and the characters outside the scene take up what their days have for the new time. */
1703
+ function skipAhead(session, config, turn, round, wall, request) {
1704
+ const span = skipTime(session, config, turn, round, wall, request);
1705
+ return {
1706
+ ...span,
1707
+ moved: catchUpRoutines(session, span.zone, span.to, turn, true)
1708
+ };
1709
+ }
1710
+ /** What a character is told of its own agenda. */
1711
+ function agendaFor(session, config, turn, wall, characterId) {
1712
+ const time = readTime(session, config, turn, wall());
1713
+ return agendaView(session, characterId, zoneOf(config), time.now);
1714
+ }
1715
+ //#endregion
1716
+ //#region src/host/clock/offscene.ts
1717
+ const HANDLED = "offscene.handled";
1718
+ const keyOf = (character) => character.sourceId ?? String(character.id);
1719
+ function handledKeys(session) {
1720
+ const stored = session.metadata.getValue(HANDLED);
1721
+ return new Set(Array.isArray(stored) ? stored.filter((entry) => typeof entry === "string") : []);
1722
+ }
1723
+ /** Remember that these were dealt with, so that they are not dealt with again. */
1724
+ function markHandled(session, keys) {
1725
+ session.metadata.setValue(HANDLED, [...handledKeys(session), ...keys].slice(-500));
1726
+ }
1727
+ /**
1728
+ * What has fallen due for characters who are not with the player and who have not dealt with it yet: commitments
1729
+ * whose time has come with everyone to do with them away from the scene, and goals whose deadline has passed.
1730
+ * Oldest first.
1731
+ */
1732
+ function dueOffScene(session, zone, now, language = "en") {
1733
+ const tr = translator(language);
1734
+ const when = (instant) => describeWhen(instant, now, zone, language);
1735
+ const handled = handledKeys(session);
1736
+ const characters = session.characters.list();
1737
+ const player = characters.find((character) => character.control === "player");
1738
+ const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1739
+ const away = (id) => playerPlace !== void 0 && session.placements.get("character", id)?.locationId !== playerPlace;
1740
+ const agents = new Map(characters.filter((character) => character.control === "agent").map((character) => [character.id, character]));
1741
+ const items = [];
1742
+ for (const engagement of session.engagements.list({
1743
+ status: "pending",
1744
+ to: now + 1
1745
+ })) {
1746
+ const key = `e${engagement.id}`;
1747
+ if (handled.has(key) || now < engagement.at + 1) continue;
1748
+ const everyone = engagement.participants;
1749
+ if (everyone.some((id) => !agents.has(id) || !away(id))) continue;
1750
+ const place = engagement.locationId === void 0 ? void 0 : session.locations.get(engagement.locationId);
1751
+ items.push({
1752
+ key,
1753
+ kind: "engagement",
1754
+ at: engagement.at,
1755
+ characters: everyone.map((id) => keyOf(agents.get(id))),
1756
+ ...place === void 0 ? {} : { place: place.sourceId ?? String(place.id) },
1757
+ text: [
1758
+ `${place === void 0 ? tr("You were to {title}, at {when}", {
1759
+ title: engagement.title,
1760
+ when: when(engagement.at)
1761
+ }) : tr("You were to {title} at {place}, at {when}", {
1762
+ title: engagement.title,
1763
+ place: place.name,
1764
+ when: when(engagement.at)
1765
+ })}${engagement.note === "" ? "" : tr(" ({note})", { note: engagement.note })}${tr(".")}`,
1766
+ now > engagement.at + ENGAGEMENT_GRACE ? tr("It is {now} now and the time has passed.", { now: when(now) }) : tr("It is {now} now.", { now: when(now) }),
1767
+ tr("It was with: {who}.", { who: everyone.map((id) => agents.get(id).name).join(tr(", ")) }),
1768
+ tr("You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.")
1769
+ ].join(" ")
1770
+ });
1771
+ }
1772
+ for (const character of agents.values()) {
1773
+ if (!away(character.id)) continue;
1774
+ for (const goal of session.intents.list(character.id, { status: "active" })) {
1775
+ const key = `g${goal.id}`;
1776
+ let deadline;
1777
+ try {
1778
+ deadline = goal.deadline === void 0 ? void 0 : parseInstant(goal.deadline, zone);
1779
+ } catch {
1780
+ deadline = void 0;
1781
+ }
1782
+ if (handled.has(key) || deadline === void 0 || deadline >= now) continue;
1783
+ items.push({
1784
+ key,
1785
+ kind: "goal",
1786
+ at: deadline,
1787
+ characters: [keyOf(character)],
1788
+ text: `${tr("The time you had for \"{goal}\" has passed ({when}; it is {now} now)", {
1789
+ goal: goal.name,
1790
+ when: when(deadline),
1791
+ now: when(now)
1792
+ })}${goal.description === "" ? "" : `${tr(": ")}${goal.description}`} ${tr("You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.")}`
1793
+ });
1794
+ }
1795
+ }
1796
+ return items.sort((a, b) => a.at - b.at);
1797
+ }
1798
+ //#endregion
1799
+ //#region src/host/variables/describe.ts
1800
+ /** What is tracked of a subject, in a line: `Health: hurt (2); Valence: unhappy (-0.4), usually even (0)`. */
1801
+ function describeShown(shown) {
1802
+ return shown.map(({ variable, value, baseline }) => {
1803
+ const usual = baseline !== void 0 && baseline !== value ? `, usually ${describeValue(variable, baseline)}` : "";
1804
+ return `${variable.name}: ${describeValue(variable, value)}${usual}`;
1805
+ }).join("; ");
1806
+ }
1807
+ //#endregion
1808
+ //#region src/host/orchestration/store.ts
1809
+ /** The rules the session copied from its world when it started. */
1810
+ function worldRules(session) {
1811
+ const value = session.metadata.getValue(WORLD_RULES_KEY);
1812
+ return Array.isArray(value) ? value.filter((rule) => typeof rule === "string") : [];
1813
+ }
1814
+ const keyOfCharacter = (character) => character.sourceId ?? String(character.id);
1815
+ function placeOf(session, characterId) {
1816
+ const placement = session.placements.get("character", characterId);
1817
+ const location = placement === void 0 ? void 0 : session.locations.get(placement.locationId);
1818
+ if (placement === void 0 || location === void 0) return void 0;
1819
+ const feature = placement.featureKey === void 0 ? void 0 : location.features.find((candidate) => candidate.key === placement.featureKey);
1820
+ return {
1821
+ location,
1822
+ position: placement.position,
1823
+ ...feature === void 0 ? {} : { feature }
1824
+ };
1825
+ }
1826
+ function castOf(session) {
1827
+ return session.characters.list().map((character) => {
1828
+ const state = session.characterStates.get(character.id);
1829
+ const place = placeOf(session, character.id);
1830
+ return {
1831
+ key: keyOfCharacter(character),
1832
+ character,
1833
+ ...state === void 0 ? {} : { state },
1834
+ ...place === void 0 ? {} : { place }
1835
+ };
1836
+ });
1837
+ }
1838
+ /** How much of what is in a container is told: a bag with fifty things in it is not recited. */
1839
+ const SHOWN_CONTENTS = 5;
1840
+ function viewOf(session, id, where) {
1841
+ const item = session.items.get(id);
1842
+ if (item === void 0) return void 0;
1843
+ const inside = item.container?.state === "open" ? session.items.contents({
1844
+ kind: "item",
1845
+ id
1846
+ }).filter((entry) => !entry.item.hidden).map((entry) => entry.item.quantity > 1 ? `${entry.item.quantity} ${entry.item.name}` : entry.item.name) : void 0;
1847
+ return {
1848
+ key: itemKey(item),
1849
+ name: item.name,
1850
+ quantity: item.quantity,
1851
+ quality: item.quality,
1852
+ notable: item.notable,
1853
+ hidden: item.hidden,
1854
+ ...item.container === void 0 ? {} : { state: item.container.state },
1855
+ ...inside === void 0 || inside.length === 0 ? {} : { contents: [...inside.slice(0, SHOWN_CONTENTS), ...inside.length > SHOWN_CONTENTS ? [`and ${inside.length - SHOWN_CONTENTS} more`] : []] },
1856
+ ...where === void 0 || where === "" ? {} : { where }
1857
+ };
1858
+ }
1859
+ /** What lies in a place, notable things first; hidden things are included only when asked for. */
1860
+ function itemsIn(session, locationId, withHidden) {
1861
+ return session.items.contents({
1862
+ kind: "location",
1863
+ id: locationId
1864
+ }).filter((entry) => withHidden || !entry.item.hidden).sort((a, b) => Number(b.item.notable) - Number(a.item.notable) || a.item.id - b.item.id).flatMap((entry) => {
1865
+ const holder = entry.holding.holder;
1866
+ const feature = holder.kind === "location" && holder.featureKey !== void 0 ? session.locations.get(locationId)?.features.find((candidate) => candidate.key === holder.featureKey)?.name : void 0;
1867
+ const where = holder.kind === "location" ? [holder.position, feature === void 0 ? void 0 : `at ${feature}`].filter((part) => part !== void 0 && part !== "").join(", ") : "";
1868
+ const view = viewOf(session, entry.item.id, where);
1869
+ return view === void 0 ? [] : [view];
1870
+ });
1871
+ }
1872
+ function carriedBy(session, characterId) {
1873
+ return session.items.contents({
1874
+ kind: "character",
1875
+ id: characterId
1876
+ }).sort((a, b) => Number(b.item.notable) - Number(a.item.notable) || a.item.id - b.item.id).flatMap((entry) => {
1877
+ const holder = entry.holding.holder;
1878
+ const view = viewOf(session, entry.item.id, holder.kind === "character" && holder.mode === "worn" ? `worn on the ${holder.slot}` : "carried");
1879
+ return view === void 0 ? [] : [view];
1880
+ });
1881
+ }
1882
+ function knowledgeOf(session, characterId, turn, visibleCharacters) {
1883
+ observeSurroundings(session, characterId, turn);
1884
+ const placement = session.placements.get("character", characterId);
1885
+ for (const otherId of visibleCharacters ?? (placement === void 0 ? [] : session.placements.at(placement.locationId, "character").map((other) => other.entityId))) if (otherId !== characterId && session.relationships.get(characterId, otherId) === void 0) session.relationships.upsert(characterId, otherId, { label: "acquaintance" }, turn);
1886
+ const locations = session.knowledge.list(characterId, "location").flatMap((entry) => {
1887
+ const place = session.locations.get(entry.subjectId);
1888
+ return place === void 0 ? [] : [place.name];
1889
+ });
1890
+ const items = session.knowledge.list(characterId, "item").flatMap((entry) => {
1891
+ const item = session.items.get(entry.subjectId);
1892
+ return item === void 0 ? [] : [item.name];
1893
+ });
1894
+ const allExits = session.locations.allExits();
1895
+ const routes = session.knowledge.list(characterId, "exit").flatMap((entry) => {
1896
+ const exit = allExits.find((candidate) => candidate.id === entry.subjectId);
1897
+ const from = exit === void 0 ? void 0 : session.locations.get(exit.fromId);
1898
+ const to = exit === void 0 ? void 0 : session.locations.get(exit.toId);
1899
+ return from === void 0 || to === void 0 ? [] : [`${from.name} -> ${to.name}`];
1900
+ });
1901
+ const characters = session.relationships.from(characterId).flatMap((relation) => {
1902
+ const character = session.characters.get(relation.toId);
1903
+ return character === void 0 ? [] : [character.name];
1904
+ });
1905
+ const factions = session.factionRelationships.from("character", characterId).filter((relation) => relation.toKind === "faction").flatMap((relation) => {
1906
+ const faction = session.factions.get(relation.toId);
1907
+ return faction === void 0 ? [] : [faction.name];
1908
+ });
1909
+ const own = new Set(session.knowledge.list(characterId, "lore").map((entry) => entry.subjectId));
1910
+ return {
1911
+ characters,
1912
+ factions,
1913
+ locations,
1914
+ items,
1915
+ routes,
1916
+ lore: session.lore.list().filter((entry) => own.has(entry.id) || entry.scope === "everyone").map((entry) => entry.title)
1917
+ };
1918
+ }
1919
+ function affiliationsOf(session, characterId) {
1920
+ return session.factionMemberships.ofCharacter(characterId).flatMap((membership) => {
1921
+ const faction = session.factions.get(membership.factionId);
1922
+ if (faction === void 0) return [];
1923
+ const relation = session.factionRelationships.get("character", characterId, "faction", faction.id);
1924
+ const relationship = relation === void 0 ? void 0 : {
1925
+ name: faction.name,
1926
+ label: relation.label,
1927
+ summary: relation.summary,
1928
+ present: false,
1929
+ familiarity: relation.familiarity,
1930
+ trust: relation.trust,
1931
+ affinity: relation.affinity,
1932
+ tension: relation.tension
1933
+ };
1934
+ return [{
1935
+ name: faction.name,
1936
+ role: membership.role,
1937
+ rank: membership.rank,
1938
+ status: membership.status,
1939
+ commitment: membership.commitment,
1940
+ publicState: session.factionStates.get(faction.id)?.publicState ?? "",
1941
+ goals: session.factionIntents.list(faction.id, { status: "active" }).map((intent) => intent.name),
1942
+ ...relationship === void 0 ? {} : { relationship }
1943
+ }];
1944
+ });
1945
+ }
1946
+ function placeViewOf(session, locationId) {
1947
+ const location = session.locations.get(locationId);
1948
+ if (location === void 0) return void 0;
1949
+ const here = new Set(session.placements.at(locationId, "character").map((placement) => placement.entityId));
1950
+ return {
1951
+ key: locationKey(location),
1952
+ location,
1953
+ exits: session.locations.exitsFrom(locationId).flatMap((exit) => {
1954
+ const to = session.locations.get(exit.toId);
1955
+ return to === void 0 ? [] : [{
1956
+ key: locationKey(to),
1957
+ name: to.name,
1958
+ exit
1959
+ }];
1960
+ }),
1961
+ here: castOf(session).filter((member) => here.has(member.character.id)),
1962
+ items: itemsIn(session, locationId, false)
1963
+ };
1964
+ }
1965
+ var DryRunDone = class extends Error {};
1966
+ /** Do the changes in order inside a transaction that is always undone, so that a later change sees the earlier ones. */
1967
+ function dryRunItems(session, entries) {
1968
+ const problems = [];
1969
+ const effects = [];
1970
+ try {
1971
+ session.transaction(() => {
1972
+ for (const entry of entries) {
1973
+ const character = session.characters.list().find((candidate) => keyOfCharacter(candidate) === entry.character);
1974
+ const mine = [];
1975
+ effects.push(mine);
1976
+ if (character === void 0) {
1977
+ problems.push(`${entry.character}: there is no such character`);
1978
+ continue;
1979
+ }
1980
+ for (const spec of entry.changes) {
1981
+ const planned = planItemChange(session, character.id, spec);
1982
+ if (!planned.ok) {
1983
+ problems.push(...planned.problems.map((problem) => `${entry.character}: cannot ${spec.action} ${spec.item}: ${problem}`));
1984
+ break;
1985
+ }
1986
+ mine.push(applyItemPlan(session, planned.plan));
1987
+ }
1988
+ }
1989
+ throw new DryRunDone();
1990
+ });
1991
+ } catch (error) {
1992
+ if (!(error instanceof DryRunDone)) throw error;
1993
+ }
1994
+ return problems.length === 0 ? {
1995
+ ok: true,
1996
+ effects
1997
+ } : {
1998
+ ok: false,
1999
+ problems
2000
+ };
2001
+ }
2002
+ /** What a character can tell of itself and of those with it, in words. */
2003
+ function trackedFor(session, characterId, presentIds) {
2004
+ const character = session.characters.get(characterId);
2005
+ return {
2006
+ self: character === void 0 ? "" : describeShown(shownVariables(session, "character", characterId, keyOfCharacter(character), "self")),
2007
+ others: presentIds.filter((id) => id !== characterId).flatMap((id) => {
2008
+ const other = session.characters.get(id);
2009
+ const text = other === void 0 ? "" : describeShown(shownVariables(session, "character", id, keyOfCharacter(other), "others"));
2010
+ return other === void 0 || text === "" ? [] : [{
2011
+ name: other.name,
2012
+ text
2013
+ }];
2014
+ })
2015
+ };
2016
+ }
2017
+ /** At most this many lines of what the story tracks are told to the game master at once. */
2018
+ const MAX_TRACKED_LINES = 14;
2019
+ /** What the story tracks, for the game master: everything, the scene first. */
2020
+ function trackedLines(session) {
2021
+ const player = session.characters.list().find((character) => character.control === "player");
2022
+ const here = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
2023
+ const near = (characterId) => here !== void 0 && session.placements.get("character", characterId)?.locationId === here ? 0 : 1;
2024
+ const lines = [];
2025
+ const world = describeShown(shownVariables(session, "world", 0, "world", "story"));
2026
+ if (world !== "") lines.push(`the world: ${world}`);
2027
+ if (here !== void 0) {
2028
+ const place = session.locations.get(here);
2029
+ const text = place === void 0 ? "" : describeShown(shownVariables(session, "location", here, locationKey(place), "story"));
2030
+ if (place !== void 0 && text !== "") lines.push(`${place.name} (${locationKey(place)}): ${text}`);
2031
+ for (const entry of session.items.contents({
2032
+ kind: "location",
2033
+ id: here
2034
+ })) {
2035
+ const text = describeShown(shownVariables(session, "item", entry.item.id, itemKey(entry.item), "story"));
2036
+ if (text !== "") lines.push(`${entry.item.name} (${itemKey(entry.item)}): ${text}`);
2037
+ }
2038
+ }
2039
+ for (const character of [...session.characters.list()].sort((a, b) => near(a.id) - near(b.id))) {
2040
+ const text = describeShown(shownVariables(session, "character", character.id, keyOfCharacter(character), "story"));
2041
+ if (text !== "") lines.push(`${character.name} (${keyOfCharacter(character)}): ${text}`);
2042
+ }
2043
+ return lines.slice(0, MAX_TRACKED_LINES);
2044
+ }
2045
+ function checkMove(session, characterKey, request) {
2046
+ const character = session.characters.list().find((candidate) => keyOfCharacter(candidate) === characterKey);
2047
+ if (character === void 0) return {
2048
+ ok: false,
2049
+ problems: [`there is no character "${characterKey}"`]
2050
+ };
2051
+ const to = session.locations.list().find((candidate) => locationKey(candidate) === request.location);
2052
+ if (to === void 0) return {
2053
+ ok: false,
2054
+ problems: [`there is no place "${request.location}" (list_locations shows the keys)`]
2055
+ };
2056
+ const move = {
2057
+ to: to.id,
2058
+ ...request.position === void 0 ? {} : { position: request.position },
2059
+ ...request.feature === void 0 ? {} : { featureKey: request.feature },
2060
+ ...request.ignoreExits === true ? { ignoreExits: true } : {}
2061
+ };
2062
+ const planned = session.planKnownMove(character.id, move);
2063
+ return planned.ok ? {
2064
+ ok: true,
2065
+ move,
2066
+ plan: planned.plan,
2067
+ to: {
2068
+ key: locationKey(to),
2069
+ name: to.name
2070
+ },
2071
+ ...request.position === void 0 ? {} : { position: request.position }
2072
+ } : {
2073
+ ok: false,
2074
+ problems: planned.problems
2075
+ };
2076
+ }
2077
+ function storeOf(session, folder, problem, queryVector, wall, prompt) {
2078
+ const settings = () => liveSettings(folder, problem);
2079
+ return {
2080
+ story: session,
2081
+ cast: () => castOf(session),
2082
+ checkMove: (character, request) => checkMove(session, character, request),
2083
+ place: (locationId) => placeViewOf(session, locationId),
2084
+ settings,
2085
+ text: (id, variables) => prompt(settings().prompts.language, id, variables),
2086
+ rules: () => rulesOf(worldRules(session), settings().rules.own),
2087
+ time: (turn) => readTime(session, settings().clock, turn, wall()),
2088
+ beginTurn: (turn) => {
2089
+ observeAsPlayer(session, turn);
2090
+ return startTurn(session, settings().clock, turn, wall());
2091
+ },
2092
+ endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum),
2093
+ skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request),
2094
+ checkVariableChanges: (changes) => changes.flatMap((spec) => {
2095
+ const planned = planVariableChange(session, spec);
2096
+ return planned.ok ? [] : planned.problems;
2097
+ }),
2098
+ changeVariables: (turn, changes) => session.transaction(() => changes.map((spec) => changeVariable(session, spec, turn))),
2099
+ trackedFor: (characterId, presentIds) => trackedFor(session, characterId, presentIds),
2100
+ tracked: () => trackedLines(session),
2101
+ dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now, languageOf$1(settings().prompts.language)),
2102
+ markHandled: (keys) => {
2103
+ markHandled(session, keys);
2104
+ },
2105
+ runTriggers: (turn, round) => {
2106
+ const settings = liveSettings(folder, problem);
2107
+ const { now, zone } = readTime(session, settings.clock, turn, wall());
2108
+ return fireTriggers(session, {
2109
+ settings,
2110
+ turn,
2111
+ round,
2112
+ now,
2113
+ zone,
2114
+ problem
2115
+ });
2116
+ },
2117
+ ...noteStore(session, () => liveSettings(folder, problem), (turn) => {
2118
+ const { now, zone } = readTime(session, liveSettings(folder, problem).clock, turn, wall());
2119
+ return {
2120
+ now,
2121
+ zone
2122
+ };
2123
+ }),
2124
+ putNote: (note) => {
2125
+ putNote(session, note);
2126
+ },
2127
+ addNote: (kind, turn, lines) => {
2128
+ addToNote(session, kind, turn, lines);
2129
+ },
2130
+ recordActivity: (entry, detail) => {
2131
+ if (detail !== void 0 && entry.run !== void 0) keepRunDetail(folder, entry.run, detail);
2132
+ forgetRunDetails(folder, recordActivity(session, entry));
2133
+ if (entry.turn !== void 0 && entry.tokens !== void 0) addUsage(session, entry.turn, "helper", entry.tokens);
2134
+ },
2135
+ recordUsage: (turn, tokens) => {
2136
+ addUsage(session, turn, "master", tokens);
2137
+ },
2138
+ notes: () => readNotes(session),
2139
+ clearNotes: () => {
2140
+ clearNotes(session);
2141
+ },
2142
+ agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId),
2143
+ commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items }) => {
2144
+ session.characterStates.update(character, patch);
2145
+ const effects = (items ?? []).map((spec) => changeItem(session, character, spec));
2146
+ if (move !== void 0) session.move(character, move);
2147
+ return effects;
2148
+ })),
2149
+ checkItemChanges: (entries) => dryRunItems(session, entries),
2150
+ carried: (characterId) => carriedBy(session, characterId),
2151
+ knowledge: (characterId, turn, visibleCharacters) => knowledgeOf(session, characterId, turn, visibleCharacters),
2152
+ affiliations: (characterId) => affiliationsOf(session, characterId),
2153
+ itemsAt: (locationId, withHidden = false) => itemsIn(session, locationId, withHidden),
2154
+ completeTurn: () => {
2155
+ session.metadata.recordTurn();
2156
+ },
2157
+ queueCommit: (record) => {
2158
+ session.pendingCommits.enqueue(record.turn, record.round, JSON.parse(JSON.stringify(record)));
2159
+ },
2160
+ pendingCommits: () => session.pendingCommits.list().map((entry) => entry.payload),
2161
+ completeCommits: (rounds) => {
2162
+ session.transaction(() => {
2163
+ session.events.seal();
2164
+ session.pendingCommits.complete(rounds);
2165
+ });
2166
+ },
2167
+ queryVector
2168
+ };
2169
+ }
2170
+ /** Opens the store of the roleplay session behind a chat; a chat that is not one gets none. */
2171
+ function storesOf(state, sessionsDir, problem = () => void 0, queryVector = () => Promise.resolve(void 0), wall = Date.now, prompt = (language, id, variables) => shippedText(id, language, variables)) {
2172
+ return (chat) => {
2173
+ const id = roleplaySessionOf(chat);
2174
+ if (id === void 0) return void 0;
2175
+ try {
2176
+ return storeOf(state.openSession(sessionsDir(), id), sessionFolder(sessionsDir(), id), problem, (text, signal) => queryVector(chat, text, signal), wall, (language, name, variables) => prompt(language, name, variables, id));
2177
+ } catch {
2178
+ return;
2179
+ }
2180
+ };
2181
+ }
2182
+ //#endregion
2183
+ //#region src/shared/ooc.ts
2184
+ /** The command or question in a player's message, or nothing when the message is an ordinary action. The request may be empty. */
2185
+ function parseOoc(text) {
2186
+ const value = text.trimStart();
2187
+ const boundary = value.search(/\s/u);
2188
+ const command = value.slice(0, boundary < 0 ? value.length : boundary).toLowerCase();
2189
+ if (command !== "/ooc" && command !== "/ask") return void 0;
2190
+ return {
2191
+ request: value.slice(command.length).trim(),
2192
+ question: command === "/ask"
2193
+ };
2194
+ }
2195
+ /** The longest answer to an out-of-character question. */
2196
+ const MAX_OOC_ANSWER = 1200;
2197
+ //#endregion
2198
+ //#region src/shared/roll.ts
2199
+ /** The roll in a player's message, or nothing when the message does not start with `/roll`. The notation may be empty, and is then refused. */
2200
+ function parseRoll(text) {
2201
+ const value = text.trimStart();
2202
+ if (value.slice(0, 5).toLowerCase() !== "/roll" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
2203
+ const body = value.slice(5).trimStart();
2204
+ const boundary = body.search(/\s/u);
2205
+ return boundary < 0 ? {
2206
+ expression: body,
2207
+ reason: ""
2208
+ } : {
2209
+ expression: body.slice(0, boundary),
2210
+ reason: body.slice(boundary).trim()
2211
+ };
2212
+ }
2213
+ //#endregion
612
2214
  //#region src/shared/tools.ts
613
2215
  /** What this version can offer. A name in a settings file or a world that is not here is kept and ignored. */
614
2216
  const OPTIONAL_TOOLS = [
@@ -677,20 +2279,6 @@ function externalEnabled(board, agent, name) {
677
2279
  return board[agent]?.[name] === true;
678
2280
  }
679
2281
  //#endregion
680
- //#region src/shared/ooc.ts
681
- /** What the player writes to speak to the game master as the author of the story: a command (`/ooc`) or a question (`/ask`), a turn of its own, never mixed with an action of the character. */
682
- const OOC_COMMAND = /^\s*\/(ooc|ask)(?=\s|$)\s*([\s\S]*)$/i;
683
- /** The command or question in a player's message, or nothing when the message is an ordinary action. The request may be empty. */
684
- function parseOoc(text) {
685
- const match = OOC_COMMAND.exec(text);
686
- return match === null ? void 0 : {
687
- request: (match[2] ?? "").trim(),
688
- question: match[1].toLowerCase() === "ask"
689
- };
690
- }
691
- /** The longest answer to an out-of-character question. */
692
- const MAX_OOC_ANSWER = 1200;
693
- //#endregion
694
2282
  //#region src/host/orchestration/character-runner.ts
695
2283
  /**
696
2284
  * Runs each character as a one-shot child of the game master. It is the character and nothing
@@ -708,6 +2296,7 @@ function characterRunner(deps) {
708
2296
  policy: settings.memory,
709
2297
  queryVector: deps.store.queryVector
710
2298
  }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)) : [];
2299
+ const background = (request.knowledge?.lore.length ?? 0) > 0 && tools.some((tool) => tool.name === "recall_my_lore");
711
2300
  const external = externalGiven(deps.parent.ctx.tools, settings.tools, "characters");
712
2301
  const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
713
2302
  return parseCharacterAction(await runChild({
@@ -724,10 +2313,22 @@ function characterRunner(deps) {
724
2313
  maxCalls: deps.store.settings().memory.lookupCalls + (external.length === 0 ? 0 : EXTERNAL_CALLS),
725
2314
  result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
726
2315
  unenforced: ["thought"],
727
- beforeSubmit: (value) => spokenIn(settings.prompts.language, value)
2316
+ beforeSubmit: submitGate(settings.prompts.language, background)
728
2317
  }));
729
2318
  };
730
2319
  }
2320
+ const BACKGROUND_CHECK = "before you answer: does this moment touch your own past, skills, training, secrets or what you know of a person or place? If it does, read that background first with recall_my_lore (about: the subject) and answer from it; if it does not, submit the same answer again unchanged";
2321
+ /** The model decides whether the moment touches its background; asking once at the point of answering is what makes it decide. */
2322
+ function submitGate(language, background) {
2323
+ let asked = !background;
2324
+ return (value) => {
2325
+ if (!asked) {
2326
+ asked = true;
2327
+ return BACKGROUND_CHECK;
2328
+ }
2329
+ return spokenIn(language, value);
2330
+ };
2331
+ }
731
2332
  /** What a character that was given tools of other plugins may call on top of its memory look-ups. */
732
2333
  const EXTERNAL_CALLS = 5;
733
2334
  /** A character whose sheet is in another language than the chat's writes in the sheet's: the answer is refused until it is in the chat's. */
@@ -738,7 +2339,42 @@ function spokenIn(language, value) {
738
2339
  intent: given.intent,
739
2340
  utterance: given.utterance,
740
2341
  account: given.account
741
- });
2342
+ }, { strays: true }) ?? narratedSpeech(given.utterance);
2343
+ }
2344
+ const CLOSING_QUOTE = {
2345
+ "\"": "\"",
2346
+ "“": "”",
2347
+ "「": "」",
2348
+ "『": "』"
2349
+ };
2350
+ function outsideQuotedSpeech(utterance) {
2351
+ const parts = [];
2352
+ let outside = 0;
2353
+ let cursor = 0;
2354
+ while (cursor < utterance.length) {
2355
+ const closing = CLOSING_QUOTE[utterance[cursor]];
2356
+ if (closing === void 0) {
2357
+ cursor += 1;
2358
+ continue;
2359
+ }
2360
+ const end = utterance.indexOf(closing, cursor + 1);
2361
+ if (end < 0) {
2362
+ cursor += 1;
2363
+ continue;
2364
+ }
2365
+ parts.push(utterance.slice(outside, cursor));
2366
+ outside = end + 1;
2367
+ cursor = outside;
2368
+ }
2369
+ parts.push(utterance.slice(outside));
2370
+ return parts;
2371
+ }
2372
+ /** Writing instructions that ask for prose from the character's own point of view lead it to put its actions between its lines; the utterance is only what is said aloud. */
2373
+ function narratedSpeech(utterance) {
2374
+ if (utterance === void 0) return void 0;
2375
+ const parts = outsideQuotedSpeech(utterance);
2376
+ if (parts.length - 1 < 2) return void 0;
2377
+ return parts.slice(1, -1).some((part) => part.replace(/[\s\p{P}]/gu, "").length >= 6) ? "the utterance holds more than the words said aloud: put what you do in intent and write in the utterance only what you say, with nothing between your lines" : void 0;
742
2378
  }
743
2379
  /** What the character was reminded of and why, for the run's record, when the recall said why. */
744
2380
  function recalledOf(request) {
@@ -793,102 +2429,6 @@ const AUTHORING_NEEDS = [
793
2429
  "trigger"
794
2430
  ];
795
2431
  //#endregion
796
- //#region src/host/pacing/director.ts
797
- const PLOTS_METADATA_KEY = "roleplay.pacing.plots";
798
- function populatePlots(metadata, plots) {
799
- const progress = plots.map((plot) => ({
800
- plot,
801
- status: plot.start,
802
- introduced: [],
803
- rejected: [],
804
- lastNudgeTurn: 0
805
- }));
806
- metadata.setValue(PLOTS_METADATA_KEY, progress);
807
- }
808
- function addSessionPlot(store, plot) {
809
- const plots = progressOf(store);
810
- if (plots.some((entry) => entry.plot.id === plot.id)) throw new Error(`there is already a plot "${plot.id}"`);
811
- plots.push({
812
- plot,
813
- status: plot.start,
814
- introduced: [],
815
- rejected: [],
816
- lastNudgeTurn: 0
817
- });
818
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
819
- }
820
- function plotAuthorNeeded(store, turn) {
821
- if (progressOf(store).length > 0 || turn < 5) return false;
822
- return store.story.events.list({
823
- fromTurn: Math.max(1, turn - 2),
824
- toTurn: turn - 1
825
- }).length === 0 && store.story.threads.list("open").length === 0;
826
- }
827
- function plotProgressOf(metadata) {
828
- const value = metadata.getValue(PLOTS_METADATA_KEY);
829
- return Array.isArray(value) ? value : [];
830
- }
831
- function progressOf(store) {
832
- return plotProgressOf(store.story.metadata);
833
- }
834
- /** Select one uncommitted possibility when the story has genuinely gone quiet; selection never makes it happen. */
835
- function pacingAdvice(store, turn) {
836
- const plots = progressOf(store);
837
- if (plots.length === 0) return void 0;
838
- const now = store.story.clock.get()?.now;
839
- const recent = store.story.events.list({
840
- fromTurn: Math.max(1, turn - 2),
841
- toTurn: turn - 1
842
- });
843
- const openThreads = store.story.threads.list("open");
844
- for (const progress of plots) {
845
- if (![
846
- "available",
847
- "engaged",
848
- "cooling"
849
- ].includes(progress.status)) continue;
850
- const quietTurns = progress.plot.pacing.quietTurns + (openThreads.length === 0 ? 0 : 2);
851
- if (recent.length > 0 || turn <= quietTurns) continue;
852
- if (turn - progress.lastNudgeTurn < progress.plot.pacing.cooldownTurns) continue;
853
- if (now !== void 0 && progress.lastNudgeAt !== void 0 && now - progress.lastNudgeAt < progress.plot.pacing.cooldownDays * 864e5) continue;
854
- const step = [...progress.plot.hooks, ...progress.plot.developments].filter((step) => !progress.introduced.includes(step.id) && !progress.rejected.includes(step.id) && step.prerequisites.every((id) => progress.introduced.includes(id)))[0];
855
- if (step === void 0) continue;
856
- const quietFor = turn - progress.lastNudgeTurn;
857
- progress.lastNudgeTurn = turn;
858
- if (now !== void 0) progress.lastNudgeAt = now;
859
- progress.status = progress.status === "available" ? "engaged" : progress.status;
860
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
861
- return {
862
- need: quietFor > progress.plot.pacing.quietTurns * 2 ? "clear" : "gentle",
863
- reason: openThreads.length === 0 ? "no recorded development or immediate thread has guided the last few turns" : "the open threads have remained without recorded development for several turns",
864
- plot: progress.plot.id,
865
- plotName: progress.plot.name,
866
- development: step.id,
867
- mode: step.mode,
868
- guidance: step.guidance || step.text,
869
- avoid: step.avoid
870
- };
871
- }
872
- }
873
- function describePacingAdvice(advice) {
874
- return `Pacing opportunity (${advice.need}; advice only, not an event): ${advice.plotName} [plot ${advice.plot}] / development ${advice.development}\nWhy now: ${advice.reason}.\nPossible nudge (${advice.mode}): ${advice.guidance}${advice.avoid.length === 0 ? "" : `\nDo not: ${advice.avoid.join("; ")}.`}\nUse it only if it fits the present scene. Do not make the player accept it, do not make a character act without activate_characters, and do not mark the development complete merely because it was offered.`;
875
- }
876
- function updatePlotProgress(store, plotId, developmentId, action) {
877
- const plots = progressOf(store);
878
- const progress = plots.find((entry) => entry.plot.id === plotId);
879
- if (progress === void 0) throw new Error(`there is no plot "${plotId}"`);
880
- if (action === "resolved" || action === "abandoned") progress.status = action;
881
- else {
882
- if (developmentId === void 0) throw new Error(`${action} needs a development`);
883
- if (![...progress.plot.hooks, ...progress.plot.developments].some((step) => step.id === developmentId)) throw new Error(`plot "${plotId}" has no development "${developmentId}"`);
884
- const target = action === "introduced" ? progress.introduced : progress.rejected;
885
- if (!target.includes(developmentId)) target.push(developmentId);
886
- if (action === "introduced") progress.status = "engaged";
887
- }
888
- store.story.metadata.setValue(PLOTS_METADATA_KEY, plots);
889
- return progress;
890
- }
891
- //#endregion
892
2432
  //#region src/host/pacing/author.ts
893
2433
  const RESULT = {
894
2434
  type: "object",
@@ -1105,7 +2645,7 @@ function renderResolution(report) {
1105
2645
  return lines.join("\n");
1106
2646
  }
1107
2647
  function renderExpansion(report) {
1108
- if (report.created.length === 0) return `Nothing was made up: ${(report.declined ?? "the world author found nothing the story needs").replace(/[.\s]+$/, "")}. Work with what exists.`;
2648
+ if (report.created.length === 0) return `Nothing was made up: ${trimCharacters((report.declined ?? "the world author found nothing the story needs").trimEnd(), ".", "end").trimEnd()}. Work with what exists.`;
1109
2649
  const lines = report.created.map((entry) => `- ${entry.kind} ${entry.key} (${entry.name})`);
1110
2650
  const characters = report.created.filter((entry) => entry.kind === "character");
1111
2651
  return [
@@ -1847,121 +3387,229 @@ function externalWithheld(registry, board, agent) {
1847
3387
  return externalTools(registry).map((tool) => tool.name).filter((name) => !externalEnabled(board, agent, name));
1848
3388
  }
1849
3389
  //#endregion
1850
- //#region src/host/sessions/activity.ts
1851
- const KEY$2 = "activity";
1852
- const isEntry = (value) => {
1853
- if (typeof value !== "object" || value === null) return false;
1854
- const entry = value;
1855
- return typeof entry["at"] === "number" && typeof entry["label"] === "string" && typeof entry["model"] === "string" && typeof entry["ms"] === "number" && typeof entry["calls"] === "number" && (entry["error"] === void 0 || typeof entry["error"] === "string");
1856
- };
1857
- /** The recorded runs, oldest first. */
1858
- function readActivity(session) {
1859
- const stored = session.metadata.getValue(KEY$2);
1860
- return Array.isArray(stored) ? stored.filter(isEntry) : [];
1861
- }
1862
- /** Files the run and returns the runs that fell off the end of the record to make room. */
1863
- function recordActivity(session, entry) {
1864
- const all = [...readActivity(session), entry];
1865
- session.metadata.setValue(KEY$2, all.slice(-60));
1866
- return all.slice(0, -60);
1867
- }
1868
- const RUN_FOLDER = "activity";
1869
- const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
1870
- const runFile = (folder, run) => {
1871
- if (!RUN_ID.test(run)) throw new RangeError(`"${run}" is not a run`);
1872
- return join(folder, RUN_FOLDER, `${run}.json`);
1873
- };
1874
- /** Stores what a helper was told and did, beside the session's database: it is bulky, and only read to find out what went wrong. */
1875
- function keepRunDetail(folder, run, detail) {
1876
- const file = runFile(folder, run);
1877
- mkdirSync(join(folder, RUN_FOLDER), { recursive: true });
1878
- writeFileSync(`${file}.tmp`, JSON.stringify(detail));
1879
- renameSync(`${file}.tmp`, file);
1880
- }
1881
- /** The stored detail of a run, or nothing when it was not kept or has been dropped. */
1882
- function readRunDetail(folder, run) {
1883
- try {
1884
- return JSON.parse(readFileSync(runFile(folder, run), "utf8"));
1885
- } catch (error) {
1886
- if (error.code === "ENOENT") return void 0;
1887
- throw error;
1888
- }
1889
- }
1890
- function forgetRunDetails(folder, dropped) {
1891
- for (const entry of dropped) if (entry.run !== void 0) rmSync(runFile(folder, entry.run), { force: true });
3390
+ //#region src/host/orchestration/hooks.ts
3391
+ const notice = (text) => createUserMessage({
3392
+ content: [{
3393
+ type: "text",
3394
+ text
3395
+ }],
3396
+ source: { kind: "roleplay" }
3397
+ });
3398
+ /** The turn of the game master of a roleplay chat; characters and other chats have none. */
3399
+ function ownerOf(agent, turn) {
3400
+ if (agent.session.header.origin === "subagent") return void 0;
3401
+ return roleplaySessionOf(agent.session.id) === void 0 ? void 0 : {
3402
+ chat: agent.session.id,
3403
+ turn
3404
+ };
1892
3405
  }
1893
- //#endregion
1894
- //#region src/host/sessions/usage.ts
1895
- const KEY$1 = "usage";
1896
- const isCount = (value) => typeof value === "object" && value !== null && [
1897
- "input",
1898
- "cached",
1899
- "output"
1900
- ].every((field) => typeof value[field] === "number");
1901
- const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
1902
- /** What each turn used, oldest first. The record belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1903
- function readUsage(session) {
1904
- const stored = session.metadata.getValue(KEY$1);
1905
- return Array.isArray(stored) ? stored.filter(isUsage) : [];
3406
+ /** Where the withdrawal of an agent's preview tool is kept: on the agent, so that a reloaded plugin still finds what its earlier self registered. */
3407
+ const PREVIEW_SHOWN = Symbol.for("dsh-agentic-roleplay.preview-tool");
3408
+ /** Registers the preview tool on the agent of a chat that shows one, once, and withdraws it when the setting is turned off. */
3409
+ function previewToggle(tool) {
3410
+ return (agent, enabled) => {
3411
+ const holder = agent;
3412
+ const withdraw = holder[PREVIEW_SHOWN];
3413
+ if (enabled && withdraw === void 0) try {
3414
+ holder[PREVIEW_SHOWN] = agent.ctx.tools.register(tool);
3415
+ } catch (error) {
3416
+ if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
3417
+ holder[PREVIEW_SHOWN] = () => void 0;
3418
+ }
3419
+ else if (!enabled && withdraw !== void 0) {
3420
+ delete holder[PREVIEW_SHOWN];
3421
+ withdraw();
3422
+ }
3423
+ };
1906
3424
  }
1907
- /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
1908
- function addUsage(session, turn, who, tokens) {
1909
- const all = readUsage(session);
1910
- const at = all.findIndex((entry) => entry.turn === turn);
1911
- const entry = at === -1 ? {
1912
- turn,
1913
- master: NO_TOKENS,
1914
- helpers: NO_TOKENS,
1915
- runs: 0
1916
- } : all[at];
1917
- const next = who === "master" ? {
1918
- ...entry,
1919
- master: addTokens(entry.master, tokens)
1920
- } : {
1921
- ...entry,
1922
- helpers: addTokens(entry.helpers, tokens),
1923
- runs: entry.runs + 1
3425
+ /** Where the withdrawals of an agent's optional tools are kept, by tool name: on the agent, so that a reloaded plugin still finds what its earlier self registered. */
3426
+ const OPTIONAL_SHOWN = Symbol.for("dsh-agentic-roleplay.optional-tools");
3427
+ /** Puts an agent's optional tools in line with the switches: registers the ones that are on and not yet there, withdraws the ones that are off. */
3428
+ function optionalToolSwitch(tools) {
3429
+ return (agent, enabled) => {
3430
+ const holder = agent;
3431
+ const shown = holder[OPTIONAL_SHOWN] ??= /* @__PURE__ */ new Map();
3432
+ for (const tool of tools) {
3433
+ const withdraw = shown.get(tool.name);
3434
+ if (enabled(tool.name) && withdraw === void 0) try {
3435
+ shown.set(tool.name, agent.ctx.tools.register(tool));
3436
+ } catch (error) {
3437
+ if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
3438
+ shown.set(tool.name, () => void 0);
3439
+ }
3440
+ else if (!enabled(tool.name) && withdraw !== void 0) {
3441
+ shown.delete(tool.name);
3442
+ withdraw();
3443
+ }
3444
+ }
1924
3445
  };
1925
- if (at === -1) all.push(next);
1926
- else all[at] = next;
1927
- all.sort((a, b) => a.turn - b.turn);
1928
- session.metadata.setValue(KEY$1, all);
1929
3446
  }
1930
- //#endregion
1931
- //#region src/host/triggers/deliver.ts
1932
- const KEY = "triggers.withdrawn";
1933
- /** Why a note was withdrawn instead of told, by the number of the note. */
1934
- function readWithdrawn(session) {
1935
- const stored = session.metadata.getValue(KEY);
1936
- if (!Array.isArray(stored)) return {};
1937
- return Object.fromEntries(stored.flatMap((entry) => {
1938
- const { note, reason } = entry ?? {};
1939
- return typeof note === "number" && typeof reason === "string" ? [[note, reason]] : [];
1940
- }));
3447
+ /** Where an agent's withdrawal of the external tools it was not given is kept: on the agent, so that a reloaded plugin still finds what its earlier self set. */
3448
+ const EXTERNAL_LIMIT = Symbol.for("dsh-agentic-roleplay.external-limit");
3449
+ /**
3450
+ * Takes away from an agent the tools other plugins registered for everyone that it was not given. A story gives the game master such tools (a file or
3451
+ * shell tool, an MCP server's) by switching them on; without it the agent has none of them. The limit follows the settings as they change.
3452
+ */
3453
+ function externalToolLimit(agent, withheld) {
3454
+ const holder = agent;
3455
+ const key = [...withheld].sort((a, b) => a.localeCompare(b)).join("\n");
3456
+ const current = holder[EXTERNAL_LIMIT];
3457
+ if (current?.key === key) return;
3458
+ current?.lift();
3459
+ delete holder[EXTERNAL_LIMIT];
3460
+ if (withheld.length > 0) holder[EXTERNAL_LIMIT] = {
3461
+ key,
3462
+ lift: agent.ctx.tools.restrict({ deny: [...withheld] })
3463
+ };
1941
3464
  }
1942
3465
  /**
1943
- * Tells these notes as the story stands now: each is written from the story at this moment, and one that no longer applies is let go and the
1944
- * reason kept (`readWithdrawn`). @returns what is to be told, with the number of its note.
3466
+ * The listeners of a roleplay preset. Preset listeners are shared by every chat
3467
+ * that uses the preset and also hear the agents that chat spawns, so each one
3468
+ * first checks that it is looking at the game master of a roleplay chat.
1945
3469
  */
1946
- function deliverNow(session, notes, clock) {
1947
- const { shown, withdrawn } = session.deliverNotes(notes, clock);
1948
- if (withdrawn.length > 0) session.transaction(() => {
1949
- for (const { note } of withdrawn) session.triggers.resolveNote(note.id, "lapsed");
1950
- const before = Object.entries(readWithdrawn(session)).map(([note, reason]) => ({
1951
- note: Number(note),
1952
- reason
1953
- }));
1954
- session.metadata.setValue(KEY, [...before, ...withdrawn.map(({ note, reason }) => ({
1955
- note: note.id,
1956
- reason
1957
- }))].slice(-100));
3470
+ function installHooks(ctx, deps) {
3471
+ const { engine, boundaries, stores, timelines, previewTool } = deps;
3472
+ const showPreviewTool = previewToggle(previewTool);
3473
+ const showOptionalTools = optionalToolSwitch(deps.optionalTools ?? []);
3474
+ /** The tools of the game master as the chat's settings say: its optional ones, and none of other plugins' that it was not given. */
3475
+ const applyTools = (agent, store) => {
3476
+ const { tools } = store.settings();
3477
+ showOptionalTools(agent, (tool) => toolEnabled(tools, "gameMaster", tool));
3478
+ externalToolLimit(agent, externalWithheld(agent.ctx.tools, tools, "gameMaster"));
3479
+ };
3480
+ ctx.on("agent/created", ({ agent }) => {
3481
+ const owner = ownerOf(agent, 0);
3482
+ const store = owner === void 0 ? void 0 : stores(owner.chat);
3483
+ if (store !== void 0) applyTools(agent, store);
3484
+ });
3485
+ ctx.on("session/event", (session, event) => {
3486
+ if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
3487
+ timelines.ended(session.id, session, event.seq);
3488
+ const events = session.snapshotEvents();
3489
+ const began = events.findLastIndex((entry) => entry.type === "turn/start");
3490
+ const start = began === -1 ? void 0 : events[began];
3491
+ if (start?.type === "turn/start") stores(session.id)?.recordUsage?.(start.data.turn, tokensOf(events.slice(began)));
3492
+ });
3493
+ ctx.on("agent/created", async ({ agent }) => {
3494
+ const { header } = agent.session;
3495
+ if (header.origin === "subagent" || !header.isSeeded || header.parentSession === void 0) return;
3496
+ if (roleplaySessionOf(agent.session.id) === void 0 || roleplaySessionOf(header.parentSession) === void 0) return;
3497
+ await timelines.adopt(agent.session.id, header.parentSession, agent.session.inheritedEventCount - 1, agent);
3498
+ });
3499
+ ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
3500
+ const owner = ownerOf(agent, turn);
3501
+ if (owner === void 0) return;
3502
+ const missing = engine.missing(owner);
3503
+ if (missing === void 0) return;
3504
+ if (!engine.object(owner)) {
3505
+ ctx.logger.warn(`roleplay: ${owner.chat} ended turn ${turn} without finishing it (${missing})`);
3506
+ return;
3507
+ }
3508
+ agent.steer(notice(`You may not end the turn yet: ${missing}.`));
3509
+ });
3510
+ ctx.on("agent/pre-step", async (payload, next) => {
3511
+ const decision = await next();
3512
+ const owner = ownerOf(payload.agent, payload.turn);
3513
+ const store = owner === void 0 ? void 0 : stores(owner.chat);
3514
+ if (owner !== void 0 && store !== void 0) {
3515
+ showPreviewTool(payload.agent, store.settings().preview.enabled);
3516
+ applyTools(payload.agent, store);
3517
+ }
3518
+ if (decision.kind !== "enter" || payload.step !== 1) return decision;
3519
+ if (owner === void 0 || store === void 0) return decision;
3520
+ const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
3521
+ await timelines.begin(owner.chat, payload.turn, text);
3522
+ const cast = store.cast();
3523
+ const ooc = parseOoc(text);
3524
+ const verdict = ooc === void 0 ? boundaries().inputValidator.validate({
3525
+ text,
3526
+ turn: payload.turn,
3527
+ cast
3528
+ }) : { ok: true };
3529
+ if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
3530
+ else if (ooc === void 0) engine.expectJudgement(owner);
3531
+ const queryVector = await store.queryVector(ooc?.request ?? text);
3532
+ store.clearNotes();
3533
+ store.lapseNotes(payload.turn);
3534
+ const { time, away, agenda } = store.beginTurn(payload.turn);
3535
+ const tr = translator(languageOf$1(store.settings().prompts.language));
3536
+ if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => tr("{name} went to {place}.", {
3537
+ name: move.name,
3538
+ place: move.to
3539
+ })));
3540
+ const world = {
3541
+ happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
3542
+ names: cue.names.join(tr(" and ")),
3543
+ text: cue.text
3544
+ }))]),
3545
+ beats: store.pendingBeats(),
3546
+ upcoming: store.upcoming(payload.turn)
3547
+ };
3548
+ const tracked = store.tracked();
3549
+ const lines = [boundaries().sceneContext.scene({
3550
+ ...tracked.length === 0 ? {} : { tracked },
3551
+ time: {
3552
+ now: time,
3553
+ agenda,
3554
+ ...away === void 0 ? {} : { away }
3555
+ },
3556
+ ...world.happened.length === 0 && world.beats.length === 0 && world.upcoming.length === 0 ? {} : { world },
3557
+ cast,
3558
+ turn: payload.turn,
3559
+ input: text,
3560
+ story: store.story,
3561
+ items: {
3562
+ at: (locationId) => store.itemsAt(locationId, true),
3563
+ carried: (characterId) => store.carried(characterId)
3564
+ },
3565
+ language: store.settings().prompts.language,
3566
+ ...queryVector === void 0 ? {} : { queryVector }
3567
+ })];
3568
+ const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
3569
+ if (pacing !== void 0) lines.push(describePacingAdvice(pacing));
3570
+ else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
3571
+ const rules = store.rules();
3572
+ if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
3573
+ const wanted = ooc === void 0 ? parseRoll(text) : void 0;
3574
+ if (wanted !== void 0) try {
3575
+ const made = rollPlain(wanted.expression);
3576
+ const roll = store.story.dice.record({
3577
+ turn: payload.turn,
3578
+ expression: made.expression,
3579
+ faces: made.faces,
3580
+ kept: made.kept,
3581
+ modifier: made.modifier,
3582
+ total: made.total,
3583
+ value: made.total,
3584
+ reason: wanted.reason === "" ? tr("the player's roll") : wanted.reason,
3585
+ by: "player"
3586
+ });
3587
+ lines.push(tr("The player rolled {dice} ({reason}) and got {total}: dice {faces}. This is a fact, decided by the dice: take it into account when you judge the attempt and decide what happens.", {
3588
+ dice: roll.expression,
3589
+ reason: roll.reason,
3590
+ total: roll.total,
3591
+ faces: `[${roll.faces.join(", ")}]`
3592
+ }));
3593
+ } catch (error) {
3594
+ engine.skip(owner);
3595
+ lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
3596
+ }
3597
+ if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
3598
+ if (ooc !== void 0 && ooc.request === "") {
3599
+ engine.skip(owner);
3600
+ lines.push(store.text("roleplay/ooc-empty", { command: ooc.question ? "/ask" : "/ooc" }));
3601
+ }
3602
+ if (!verdict.ok) {
3603
+ engine.skip(owner);
3604
+ lines.push(store.text("roleplay/input-refused", { reason: verdict.reason }));
3605
+ }
3606
+ return {
3607
+ ...decision,
3608
+ messages: [...decision.messages, notice(lines.join("\n\n"))]
3609
+ };
1958
3610
  });
1959
- return shown.map(({ note, text }) => ({
1960
- id: note.id,
1961
- text
1962
- }));
1963
3611
  }
1964
3612
  //#endregion
1965
- export { observeAsPlayer as A, RESULTS as B, parseOoc as C, notesOfSession as D, clearNotes as E, describeWhen as F, languageOf as H, endRound as I, readTime as L, ClockError as M, beginTurn as N, putNote as O, describeTime as P, skipTime as R, MAX_OOC_ANSWER as S, addToNote as T, translator as U, answerLimits as V, pacingAdvice as _, forgetRunDetails as a, populatePlots as b, readRunDetail as c, externalTools as d, externalWithheld as f, describePacingAdvice as g, PLOTS_METADATA_KEY as h, readUsage as i, observeSurroundings as j, readNotes as k, recordActivity as l, createTools$1 as m, readWithdrawn as n, keepRunDetail as o, PREVIEW_TOOL as p, addUsage as r, readActivity as s, deliverNow as t, externalGiven as u, plotAuthorNeeded as v, toolEnabled as w, AUTHORING_NEEDS as x, plotProgressOf as y, zoneOf as z };
3613
+ export { shippedPromptsDirectory as $, populatePlots as A, readDocument as B, describeTime as C, answerLimits as D, RESULTS as E, wrongLanguage as F, PROMPTS_FOLDER as G, formatIssue as H, PLOTS_FILE_NAME as I, inheritPrompts as J, PromptLibrary as K, loadPlots as L, STORY_LANGUAGES as M, isStoryLanguage as N, PLOTS_METADATA_KEY as O, textLanguage as P, shippedLanguages as Q, parsePlotsFile as R, ClockError as S, zoneOf as T, errorMessage as U, Reader as V, LANGUAGE_FOLDER as W, listFiles as X, languageOf as Y, promptProblem as Z, readWithdrawn as _, externalWithheld as a, SessionNotFoundError as at, readNotes as b, AUTHORING_NEEDS as c, translator as ct, storesOf as d, AgentUnavailableError as et, readUsage as f, writeVerdicts as g, readVerdicts as h, externalTools as i, SessionArchivedError as it, LANGUAGE_NAMES as j, plotProgressOf as k, toolEnabled as l, readRunDetail as m, installHooks as n, InvalidWorldError as nt, PREVIEW_TOOL as o, WorldNotFoundError as ot, readActivity as p, copyWorldPrompts as q, externalGiven as r, ReflectionRefusedError as rt, createTools$1 as s, languageOf$1 as st, externalToolLimit as t, InvalidStartError as tt, MAX_OOC_ANSWER as u, addToNote as v, describeWhen as w, observeAsPlayer as x, notesOfSession as y, plotReferenceProblems as z };
1966
3614
 
1967
- //# sourceMappingURL=deliver-Cl6bjp7g.js.map
3615
+ //# sourceMappingURL=hooks-B2EhBS_-.js.map