@dsh-agentic-roleplay/core 0.11.0 → 0.12.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 (62) hide show
  1. package/lib/{access-CXtaZNbx.js → access-DAw54-NI.js} +6 -15
  2. package/lib/{authoring-tools--6V1pIIL.js → authoring-tools-4NgDhIJV.js} +116 -13
  3. package/lib/authoring.js +38 -8
  4. package/lib/{child-C9nPIy9j.js → child-D3QUNb3m.js} +121 -2
  5. package/lib/client.js +1389 -475
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-CtG-bDzz.js → gallery-Ct6nm4UQ.js} +3 -3
  10. package/lib/{generator-nLoPM5MF.js → generator-CI8fOnXy.js} +9 -3
  11. package/lib/helper.js +22 -1
  12. package/lib/{hooks-DORky4KT.js → hooks-BNeoGMHZ.js} +1342 -293
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +444 -24
  15. package/lib/jail-BIF79PJO.js +107 -0
  16. package/lib/{library-CH-ahlm0.js → library-BF9ZMSFz.js} +3 -3
  17. package/lib/{lorebook-author-tools-BrVde1N-.js → lorebook-author-tools-DBk-V0hp.js} +7 -7
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-B0hConSw.js → narration-xvErE2yp.js} +34 -3
  20. package/lib/orchestration.js +915 -59
  21. package/lib/{pack-jail-Bk82pX9t.js → pack-jail-C8EyX9Ix.js} +18 -14
  22. package/lib/{packs-ELfh8yh1.js → packs-S0SzrVv-.js} +2 -2
  23. package/lib/{presenter-agent-UKbKYXMO.js → presenter-agent-Bc478nTA.js} +11 -8
  24. package/lib/{preset-D9Sfc8sf.js → preset-SJZyw0kt.js} +4 -4
  25. package/lib/{preset-author-tools-B3pFL1-e.js → preset-author-tools-CzogjK42.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-BRt4Xsy4.js → presets-DQ5rioMh.js} +251 -49
  28. package/lib/{reflection-CHiHsY4Y.js → reflection-buQiSdvq.js} +17 -609
  29. package/lib/service-mRKwpWjX.js +140 -0
  30. package/lib/{text-CzqhC8sT.js → text-Dfv8S8eq.js} +36 -2
  31. package/lib/{turn-guard-B53qOWEU.js → turn-guard-BSAba8sp.js} +3 -3
  32. package/package.json +3 -3
  33. package/prompts/en/import/finish-ok.md +1 -1
  34. package/prompts/en/import/generator.md +1 -1
  35. package/prompts/en/import/style.md +1 -1
  36. package/prompts/en/import/variables.md +3 -1
  37. package/prompts/en/roleplay/character-decide.md +1 -1
  38. package/prompts/en/roleplay/character-lookup.md +1 -1
  39. package/prompts/en/roleplay/decide-errand.md +1 -0
  40. package/prompts/en/roleplay/decide-message.md +1 -0
  41. package/prompts/en/roleplay/decide-reuse.md +3 -0
  42. package/prompts/en/roleplay/decide-variable.md +1 -0
  43. package/prompts/en/roleplay/dream.md +1 -0
  44. package/prompts/en/roleplay/gate-repeat.md +1 -0
  45. package/prompts/en/roleplay/image-presenter.md +1 -0
  46. package/prompts/en/roleplay/track-values.md +1 -0
  47. package/prompts/en/roleplay/track-variables.md +1 -0
  48. package/prompts/zh/import/finish-ok.md +1 -1
  49. package/prompts/zh/import/generator.md +1 -1
  50. package/prompts/zh/import/style.md +1 -1
  51. package/prompts/zh/import/variables.md +3 -1
  52. package/prompts/zh/roleplay/character-decide.md +1 -1
  53. package/prompts/zh/roleplay/character-lookup.md +1 -1
  54. package/prompts/zh/roleplay/decide-errand.md +1 -0
  55. package/prompts/zh/roleplay/decide-message.md +1 -0
  56. package/prompts/zh/roleplay/decide-reuse.md +3 -0
  57. package/prompts/zh/roleplay/decide-variable.md +1 -0
  58. package/prompts/zh/roleplay/dream.md +1 -0
  59. package/prompts/zh/roleplay/gate-repeat.md +1 -0
  60. package/prompts/zh/roleplay/image-presenter.md +1 -0
  61. package/prompts/zh/roleplay/track-values.md +1 -0
  62. package/prompts/zh/roleplay/track-variables.md +1 -0
@@ -1,16 +1,18 @@
1
- import { c as chatSessionId, l as roleplaySessionOf, t as promptFor } from "./access-CXtaZNbx.js";
2
- import { B as COMMANDS_KEY, H as commandsOf, P as wrongLanguage, T as RESULTS, V as commandFlagKey, c as record, dt as ClockError, f as MAX_OOC_ANSWER, ht as AUTHORING_NEEDS, l as characterRunner, mt as zoneOf, n as installHooks, o as PREVIEW_TOOL, p as storesOf, pt as describeWhen, r as externalGiven, rt as shippedText, s as createTools$1, st as ReflectionRefusedError, u as toolEnabled, v as readVerdicts, y as writeVerdicts } from "./hooks-DORky4KT.js";
3
- import { E as tokensOf, S as currentTurn, T as estimateAnswer, a as childTrace, l as runChild, n as childModel, r as childSampling } from "./child-C9nPIy9j.js";
4
- import { a as whereabouts, m as referent, n as memoryReflector, p as sameWords, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-CHiHsY4Y.js";
5
- import { B as modeFor, H as routeVerdicts, L as announceProblem, R as askYesNo, U as yesAt, V as noAt, Vt as INTENT_STATUSES, m as STANDING_PROMPT } from "./presets-BRt4Xsy4.js";
6
- import { i as translator, r as languageOf } from "./text-CzqhC8sT.js";
7
- import { a as liveSettings, g as GATE_SITES, n as encodeOutput } from "./narration-B0hConSw.js";
8
- import { C as slug, T as uniqueKey, t as addToLibrary } from "./library-CH-ahlm0.js";
9
- import { _ as API_PREFIX } from "./packs-ELfh8yh1.js";
10
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CtG-bDzz.js";
11
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-UKbKYXMO.js";
1
+ import { t as promptFor } from "./access-DAw54-NI.js";
2
+ import { D as referent, E as sameWords, H as COMMANDS_KEY, I as wrongLanguage, O as RESULTS, U as commandFlagKey, W as commandsOf, a as externalGiven, at as shippedText, c as PREVIEW_TOOL, d as toolEnabled, et as languageOf, f as MAX_OOC_ANSWER, gt as AUTHORING_NEEDS, ht as zoneOf, i as characterRunner, l as createTools$1, lt as ReflectionRefusedError, mt as describeWhen, n as installHooks, p as storesOf, pt as ClockError, u as record, v as readVerdicts, y as writeVerdicts } from "./hooks-BNeoGMHZ.js";
3
+ import { A as chatSessionId, O as estimateAnswer, T as currentTurn, a as childTrace, d as sessionOfChat, f as tracerOf, j as roleplaySessionOf, k as tokensOf, l as runChild, n as childModel, r as childSampling, u as TurnTraces } from "./child-D3QUNb3m.js";
4
+ import { a as whereabouts, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-buQiSdvq.js";
5
+ import { B as modeFor, H as routeVerdicts, L as announceProblem, R as askYesNo, U as yesAt, V as noAt, Wt as INTENT_STATUSES, dt as splitPanels, m as STANDING_PROMPT, zt as guarded } from "./presets-DQ5rioMh.js";
6
+ import { a as liveSettings, g as GATE_SITES, n as encodeOutput } from "./narration-xvErE2yp.js";
7
+ import { i as translator, r as languageOf$1 } from "./text-Dfv8S8eq.js";
8
+ import { t as registerFoldersJail } from "./jail-BIF79PJO.js";
9
+ import { a as workspaceOf, n as storyRoots } from "./service-mRKwpWjX.js";
10
+ import { C as slug, T as uniqueKey, t as addToLibrary } from "./library-BF9ZMSFz.js";
11
+ import { _ as API_PREFIX } from "./packs-S0SzrVv-.js";
12
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-Ct6nm4UQ.js";
13
+ import { c as presentedFor, i as findImages, n as interpretImage, s as present, t as runImagePresenter } from "./presenter-agent-Bc478nTA.js";
12
14
  import { join } from "node:path";
13
- import { InvalidEditError, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, parseRecordsEdit, rollForCheck, sessionDatabase, sessionFolder, systemRoller } from "@dsh-agentic-roleplay/state";
15
+ import { InvalidEditError, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, parseRecordsEdit, rollForCheck, seededRoll, sessionDatabase, sessionFolder, systemRoller } from "@dsh-agentic-roleplay/state";
14
16
  import { existsSync } from "node:fs";
15
17
  import { createHash } from "node:crypto";
16
18
  import { readdir } from "node:fs/promises";
@@ -192,7 +194,7 @@ function describePrompt(job, memory) {
192
194
  ...records.open_threads.length === 0 ? ["- none"] : records.open_threads.map((thread) => `- id ${thread.id}: ${thread.text}`)
193
195
  ].join("\n");
194
196
  }
195
- const RESULT$4 = {
197
+ const RESULT$5 = {
196
198
  type: "object",
197
199
  properties: {
198
200
  complete: {
@@ -339,7 +341,7 @@ function recordKeeper(deps) {
339
341
  prompt: describePrompt(job, memory),
340
342
  tools: keeperTools(job, memory, progress),
341
343
  external: externalGiven(parent.ctx.tools, job.store.settings().tools, "records"),
342
- result: RESULT$4,
344
+ result: RESULT$5,
343
345
  beforeSubmit: () => {
344
346
  if (progress.edits === 0 && !warned && job.store.story.records({ rounds: job.rounds.map(({ turn, round }) => ({
345
347
  turn,
@@ -370,7 +372,7 @@ function suggestionProblems(lines, wanted) {
370
372
  /** One short line each: whitespace is collapsed. */
371
373
  const tidySuggestions = (lines) => lines.map((line) => line.trim().replace(/\s+/g, " "));
372
374
  // src/host/orchestration/suggester.ts
373
- const RESULT$3 = {
375
+ const RESULT$4 = {
374
376
  type: "object",
375
377
  properties: { options: {
376
378
  type: "array",
@@ -396,11 +398,13 @@ function promptOf(job) {
396
398
  ].join("\n");
397
399
  }
398
400
  /** Offers the player what to do next from what they just read, with an agent of its own, in the background of the story. */
401
+ /** The first `count` lines, tidied. */
402
+ const wanted = (options, count) => tidySuggestions(options).slice(0, count);
399
403
  function suggestionWriter(deps) {
400
404
  return { async suggest(job, signal) {
401
405
  const parent = deps.agentOf(job.chat);
402
406
  if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
403
- return (await runChild({
407
+ const result = await runChild({
404
408
  parent,
405
409
  signal,
406
410
  reasoningEffort: job.store.settings().reasoning.children,
@@ -410,17 +414,19 @@ function suggestionWriter(deps) {
410
414
  trace: childTrace(job.store, "suggestions", "suggestions"),
411
415
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
412
416
  prompt: promptOf(job),
413
- result: RESULT$3,
417
+ result: RESULT$4,
418
+ structured: true,
414
419
  beforeSubmit: (value) => {
415
- const problems = suggestionProblems(tidySuggestions(value.options), job.count);
420
+ const problems = suggestionProblems(wanted(value.options, job.count), job.count);
416
421
  return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
417
422
  },
418
423
  maxCalls: 3
419
- })).options;
424
+ });
425
+ return wanted(result.options, job.count);
420
426
  } };
421
427
  }
422
428
  // src/host/triggers/judge.ts
423
- const RESULT$2 = {
429
+ const RESULT$3 = {
424
430
  type: "object",
425
431
  properties: { verdicts: {
426
432
  type: "array",
@@ -450,7 +456,7 @@ const RESULT$2 = {
450
456
  additionalProperties: false
451
457
  };
452
458
  /** The longest reason a verdict gives, in characters: what the answer is given room for besides its number and its yes or no. */
453
- const REASON_CHARS$1 = 600;
459
+ const REASON_CHARS$2 = 600;
454
460
  /** The statements of the triggers still waiting, each once. */
455
461
  function waitingStatements(job) {
456
462
  return [...new Set(job.store.story.triggers.list({ status: "dormant" }).flatMap((trigger) => judgedStatements(trigger.condition)))];
@@ -462,7 +468,7 @@ function sceneOf(job) {
462
468
  cast: job.store.cast().map((member) => `${member.character.name}${member.place === void 0 ? "" : ` (at ${member.place.location.name})`}${member.state === void 0 ? "" : `: ${[member.state.publicState, member.state.activity].filter((text) => text !== "").join("; ")}`}`)
463
469
  };
464
470
  }
465
- function brief$1(scene, statements) {
471
+ function brief$2(scene, statements) {
466
472
  return [
467
473
  "Statements to judge:",
468
474
  ...statements.map((statement, index) => `${index + 1}. ${statement}`),
@@ -499,15 +505,15 @@ function triggerJudge(deps) {
499
505
  turn: job.turn,
500
506
  reasoningEffort: settings.reasoning.children,
501
507
  sampling: childSampling(settings, "records", estimateAnswer(subset.flatMap(() => [
502
- REASON_CHARS$1,
508
+ REASON_CHARS$2,
503
509
  0,
504
510
  0
505
511
  ]), settings.prompts.language)),
506
512
  ...childModel(settings, "records"),
507
513
  trace: childTrace(store, "records", "trigger judge"),
508
514
  persona: promptFor(parent, "roleplay/trigger-judge", settings.prompts.language),
509
- prompt: brief$1(scene, subset),
510
- result: RESULT$2,
515
+ prompt: brief$2(scene, subset),
516
+ result: RESULT$3,
511
517
  beforeSubmit: (value) => {
512
518
  const numbers = value.verdicts.map((verdict) => verdict.number);
513
519
  const missing = subset.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
@@ -629,6 +635,105 @@ function ruleChecks(deps) {
629
635
  return found.map((key) => rules[Number(key.slice(4))]);
630
636
  } };
631
637
  }
638
+ // src/host/decisions/repeats.ts
639
+ const PROMPT$1 = "roleplay/gate-repeat";
640
+ const REASON_CHARS$1 = 300;
641
+ const GATE_BAND$1 = .15;
642
+ const sentencesOf = (text) => text.split(/\n+|(?<=[.!?。!?…])\s*/).map((sentence) => sentence.trim()).filter((sentence) => sentence !== "");
643
+ const keyOf$1 = (sentence) => sentence.toLowerCase().replace(/\s+/g, " ");
644
+ /** The sentences of the narration that an earlier turn, or an earlier place in the same narration, already told, as written now and once each. */
645
+ function repeatedSentences(narration, earlier, minChars) {
646
+ const told = new Set(earlier.flatMap((text) => sentencesOf(text).map(keyOf$1)));
647
+ const found = /* @__PURE__ */ new Map();
648
+ for (const sentence of sentencesOf(narration)) {
649
+ const key = keyOf$1(sentence);
650
+ if (key.length < minChars) continue;
651
+ if (told.has(key) && !found.has(key)) found.set(key, sentence);
652
+ told.add(key);
653
+ }
654
+ return [...found.values()];
655
+ }
656
+ const RESULT$2 = {
657
+ type: "object",
658
+ properties: {
659
+ reason: {
660
+ type: "string",
661
+ description: "One short sentence, written first: which of the numbered sentences are stock lines used again for want of something new, and which are meant."
662
+ },
663
+ stale: {
664
+ type: "array",
665
+ items: { type: "integer" },
666
+ description: "The numbers of the sentences that are stale filler; empty when every repeat is meant."
667
+ }
668
+ },
669
+ required: ["reason", "stale"],
670
+ additionalProperties: false
671
+ };
672
+ const asFinding = (stale) => stale.length === 0 ? [] : [{
673
+ gate: "repeats",
674
+ message: `the narration tells again, in the same words, ${stale.map((sentence) => `"${sentence}"`).join("; ")}, which an earlier turn already used: say it differently, or leave it out if nothing new is to be said`
675
+ }];
676
+ /**
677
+ * The sentences of the narration that an earlier turn told in the same words, when the chat has `decisions.repeats` on. A sentence found by code is
678
+ * stale or meant: `strict` counts every one as stale with no model; any other mode has the language model, the decision model or both say which.
679
+ */
680
+ async function repeatFindings(job, deps, signal) {
681
+ const settings = job.store.settings();
682
+ const mode = settings.decisions.repeats;
683
+ if (mode === "off" || job.narration.trim() === "") return [];
684
+ const earlier = deps.earlier(job.chat, settings.decisions.repeatTurns);
685
+ const candidates = repeatedSentences(job.narration, earlier, settings.decisions.repeatChars).slice(0, 6);
686
+ if (candidates.length === 0) return [];
687
+ if (mode === "strict") return asFinding(candidates);
688
+ const keys = candidates.map((_, index) => `repeat${index}`);
689
+ const shown = (sentence) => earlier.filter((text) => text.toLowerCase().includes(sentence.toLowerCase())).join("\n").slice(-1500);
690
+ try {
691
+ const routed = await routeVerdicts({
692
+ mode,
693
+ yesAt: settings.decisions.gateThreshold,
694
+ noAt: Math.max(0, settings.decisions.gateThreshold - GATE_BAND$1),
695
+ turn: job.turn,
696
+ keys,
697
+ what: (key) => candidates[Number(key.slice(6))],
698
+ probabilities: async () => {
699
+ const service = deps.decisions?.();
700
+ if (service === void 0) throw new Error("no decision service is selected, or the selected one is not loaded");
701
+ const state = {
702
+ narration: job.narration,
703
+ earlier_turns: earlier.join("\n").slice(-1500)
704
+ };
705
+ return await askYesNo(service, state, candidates.map((sentence, index) => ({
706
+ key: keys[index],
707
+ instructions: job.store.text(PROMPT$1, { sentence })
708
+ })), signal);
709
+ },
710
+ llm: async () => {
711
+ const parent = deps.agentOf(job.chat);
712
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
713
+ const answer = await runChild({
714
+ parent,
715
+ signal,
716
+ reasoningEffort: settings.reasoning.children,
717
+ sampling: childSampling(settings, "records", estimateAnswer([REASON_CHARS$1, 0], settings.prompts.language)),
718
+ ...childModel(settings, "records"),
719
+ trace: childTrace(job.store, "records", "repeats check"),
720
+ persona: `${promptFor(parent, PROMPT$1, settings.prompts.language, { sentence: "each numbered sentence" })}\n\nGive your reason in one short sentence first, then the numbers of the sentences that are stale filler.`,
721
+ prompt: `The narration:\n${job.narration}\n\nThe sentences told in an earlier turn:\n${candidates.map((sentence, index) => `${index + 1}. ${sentence}\n Earlier: ${shown(sentence).slice(-300)}`).join("\n")}`,
722
+ result: RESULT$2,
723
+ maxCalls: 2
724
+ });
725
+ return new Map(keys.map((key, index) => [key, answer.stale.includes(index + 1)]));
726
+ }
727
+ }, signal);
728
+ announceProblem(deps.seen, `${job.chat}:repeats`, routed.report, deps.problem);
729
+ job.store.recordDecisions?.("repeats", routed.report);
730
+ return asFinding(candidates.filter((_, index) => routed.verdicts.get(keys[index]) === true));
731
+ } catch (error) {
732
+ if (signal.aborted) throw error;
733
+ deps.problem?.(`the repeats check of turn ${job.turn} could not be made, the output goes on as it is: ${error instanceof Error ? error.message : String(error)}`);
734
+ return [];
735
+ }
736
+ }
632
737
  // src/host/decisions/gates.ts
633
738
  /**
634
739
  * How far below the threshold a probability may fall and still be not sure. A decision model gives a rare fault a low probability even when it
@@ -684,7 +789,7 @@ function outputGates(deps) {
684
789
  return { async check(job, signal) {
685
790
  const settings = job.store.settings();
686
791
  const parent = deps.agentOf(job.chat);
687
- return [...(await Promise.all(GATE_SITES.map(async (site) => {
792
+ const found = await Promise.all(GATE_SITES.map(async (site) => {
688
793
  const mode = settings.decisions[site];
689
794
  const gate = GATES[site];
690
795
  if (mode === "off" || !gate.applies(job)) return [];
@@ -733,7 +838,19 @@ function outputGates(deps) {
733
838
  deps.problem?.(`the ${site} check of turn ${job.turn} could not be made, the output goes on as it is: ${error instanceof Error ? error.message : String(error)}`);
734
839
  return [];
735
840
  }
736
- }))).flat(), ...await secretFindings(job, settings.decisions, deps.decisions?.(), seen, signal, deps.problem)];
841
+ }));
842
+ const repeats = await repeatFindings(job, {
843
+ agentOf: deps.agentOf,
844
+ ...deps.decisions === void 0 ? {} : { decisions: deps.decisions },
845
+ earlier: deps.earlier ?? (() => []),
846
+ seen,
847
+ ...deps.problem === void 0 ? {} : { problem: deps.problem }
848
+ }, signal);
849
+ return [
850
+ ...found.flat(),
851
+ ...repeats,
852
+ ...await secretFindings(job, settings.decisions, deps.decisions?.(), seen, signal, deps.problem)
853
+ ];
737
854
  } };
738
855
  }
739
856
  const SECRET_PROMPT = "roleplay/gate-secret";
@@ -753,6 +870,245 @@ async function secretFindings(job, decisions, service, seen, signal, say) {
753
870
  message: `the output may give away what ${job.player === "" ? "the player's character" : job.player} does not know yet (${titles.join("; ")}): show only what can be seen or heard, and let the rest be learned in the story; if this is meant to be revealed now, deliver it again unchanged`
754
871
  }];
755
872
  }
873
+ // src/host/variables/tracker.ts
874
+ /** How far below the threshold a probability may fall and still be not sure: the same band as the other checks of what happened. */
875
+ const BAND = .15;
876
+ /** What the models are shown of the turn, in characters: enough for what happened, never the whole story. */
877
+ const NARRATION_CHARS$1 = 2400;
878
+ const DEEDS_CHARS = 2400;
879
+ /** One true-or-false for each key, named by the key: a list of {key, changed} was written by the server with `changed` before `key` (alphabetical), so the answer came before the question and was no for all of them. */
880
+ const verdictSchema = (keys) => ({
881
+ type: "object",
882
+ properties: Object.fromEntries(keys.map((key) => [key, { type: "boolean" }])),
883
+ required: [...keys],
884
+ additionalProperties: false
885
+ });
886
+ /** The new value of each changed key, typed by what the value is: a free choice of types let the model write a number as text, which the story refused. */
887
+ const valuesSchema = (items) => ({
888
+ type: "object",
889
+ properties: Object.fromEntries(items.map((item) => {
890
+ const { variable } = item;
891
+ if (variable.kind === "flag") return [item.key, { type: "boolean" }];
892
+ if (variable.kind === "choice") return [item.key, {
893
+ type: "string",
894
+ enum: [...variable.options]
895
+ }];
896
+ return [item.key, { type: variable.integer ? "integer" : "number" }];
897
+ })),
898
+ required: items.map((item) => item.key),
899
+ additionalProperties: false
900
+ });
901
+ const shown = (value) => typeof value === "boolean" ? value ? "true" : "false" : String(value);
902
+ /**
903
+ * The values to look at after a turn: every value the world declared (not the built-in feelings, which the characters' own answers carry) for the world and for the player's character and the
904
+ * characters the turn names (`scene` is what it said), where it applies.
905
+ */
906
+ function trackedItems(store, scene = "") {
907
+ const { variables } = store.story;
908
+ const cast = store.cast().filter((member) => member.character.control === "player" || scene.toLowerCase().includes(member.character.name.toLowerCase())).map((member) => ({
909
+ key: member.key,
910
+ name: member.character.name,
911
+ id: member.character.id
912
+ }));
913
+ return variables.defs().filter((def) => !def.builtin).flatMap((def) => {
914
+ return (def.subject === "world" ? [{
915
+ key: "world",
916
+ name: "",
917
+ id: 0
918
+ }] : def.subject === "character" ? cast : []).filter((subject) => variables.applies(def, def.subject, subject.id)).map((subject) => ({
919
+ key: `${def.key}:${subject.key}`,
920
+ variable: def,
921
+ subject: {
922
+ key: subject.key,
923
+ name: subject.name
924
+ },
925
+ value: variables.value(def.key, def.subject, subject.id)
926
+ }));
927
+ });
928
+ }
929
+ /** How the value changes, as the world says it, with the space that sets it apart from the description; nothing when the world gives no rule. */
930
+ const ruleOf = (def, tr) => def.update.trim() === "" ? "" : ` ${tr("Changes: {rule}", { rule: def.update.trim() })}`;
931
+ const ownerOf = (item, tr) => item.subject.key === "world" ? tr("the story") : item.subject.name;
932
+ function question(store, item, tr) {
933
+ return store.text("roleplay/decide-variable", {
934
+ subject: ownerOf(item, tr),
935
+ name: item.variable.name,
936
+ description: item.variable.description,
937
+ update: ruleOf(item.variable, tr),
938
+ value: shown(item.value)
939
+ });
940
+ }
941
+ /** What the language model is told of the turn, then the values it is asked about. */
942
+ function brief$1(job, items, tr, heading) {
943
+ const range = (def) => def.kind === "number" ? ` (${def.min ?? "…"} to ${def.max ?? "…"}${def.integer ? ", whole numbers" : ""})` : def.kind === "choice" ? ` (${def.options.join(", ")})` : "";
944
+ return [
945
+ job.input.trim() === "" ? void 0 : `${tr("What the player wrote:")}\n${job.input.slice(0, NARRATION_CHARS$1)}`,
946
+ `${tr("What the characters did and said:")}\n${job.deeds.join("\n").slice(0, DEEDS_CHARS)}`,
947
+ `${tr("What the player read:")}\n${job.narration.slice(0, NARRATION_CHARS$1)}`,
948
+ `${heading}\n${items.map((item) => `- ${item.key}: ${ownerOf(item, tr)}, ${item.variable.name}${range(item.variable)}. ${item.variable.description}${ruleOf(item.variable, tr)} ${tr("Now: {value}.", { value: shown(item.value) })}`).join("\n")}`
949
+ ].filter((part) => part !== void 0).join("\n\n");
950
+ }
951
+ /**
952
+ * Looks at the values the story tracks after each turn (`decisions.variables`): one question for each value and each person it applies to, whether what happened changed it, put to the
953
+ * language model, the decision model or both as the setting says; the language model then gives the new value of those that did. The game master changes a value only when it thinks of
954
+ * it; this makes sure every value is looked at. A failure is reported and leaves the values as they were.
955
+ */
956
+ function variableTracker(deps) {
957
+ const seen = /* @__PURE__ */ new Map();
958
+ return { async track(job, signal) {
959
+ const settings = job.store.settings();
960
+ const mode = settings.decisions.variables;
961
+ if (mode === "off") return 0;
962
+ const items = trackedItems(job.store, `${job.input}\n${job.deeds.join("\n")}\n${job.narration}`);
963
+ if (items.length === 0) return 0;
964
+ const parent = deps.agentOf(job.chat);
965
+ const tr = translator(languageOf$1(settings.prompts.language));
966
+ const byKey = new Map(items.map((item) => [item.key, item]));
967
+ const personaOf = (id) => parent === void 0 ? job.store.text(id) : promptFor(parent, id, settings.prompts.language);
968
+ const ask = async (persona, prompt, result, answers, label) => {
969
+ if (deps.ask !== void 0) return await deps.ask({
970
+ persona,
971
+ prompt,
972
+ result,
973
+ label
974
+ });
975
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
976
+ return await runChild({
977
+ parent,
978
+ signal,
979
+ reasoningEffort: settings.reasoning.children,
980
+ sampling: childSampling(settings, "records", estimateAnswer(Array.from({ length: answers }, () => 40), settings.prompts.language)),
981
+ ...childModel(settings, "records"),
982
+ trace: childTrace(job.store, "records", label),
983
+ turn: job.turn,
984
+ structured: true,
985
+ persona,
986
+ prompt,
987
+ result,
988
+ maxCalls: 2
989
+ });
990
+ };
991
+ try {
992
+ const routed = await routeVerdicts({
993
+ mode,
994
+ yesAt: settings.decisions.gateThreshold,
995
+ noAt: Math.max(0, settings.decisions.gateThreshold - BAND),
996
+ turn: job.turn,
997
+ keys: items.map((item) => item.key),
998
+ what: (key) => `${byKey.get(key).variable.name}: ${byKey.get(key).subject.name}`,
999
+ probabilities: async (keys) => {
1000
+ const service = deps.decisions?.();
1001
+ if (service === void 0) throw new Error("no decision service is selected, or the selected one is not loaded");
1002
+ const state = {
1003
+ happened: job.deeds.join("\n").slice(0, DEEDS_CHARS),
1004
+ narration: job.narration.slice(0, NARRATION_CHARS$1),
1005
+ ...job.input.trim() === "" ? {} : { player_wrote: job.input }
1006
+ };
1007
+ return await askYesNo(service, state, keys.map((key) => ({
1008
+ key,
1009
+ instructions: question(job.store, byKey.get(key), tr)
1010
+ })), signal);
1011
+ },
1012
+ llm: async (keys) => {
1013
+ const asked = keys.map((key) => byKey.get(key));
1014
+ const answer = await ask(personaOf("roleplay/track-variables"), brief$1(job, asked, tr, tr("The values to look at:")), verdictSchema(keys), asked.length, "tracked values");
1015
+ return new Map(keys.map((key) => [key, answer[key] === true]));
1016
+ }
1017
+ }, signal);
1018
+ announceProblem(seen, `${job.chat}:variables`, routed.report, deps.problem);
1019
+ job.store.recordDecisions?.("variables", routed.report);
1020
+ const changed = items.filter((item) => routed.verdicts.get(item.key) === true);
1021
+ if (changed.length === 0) return 0;
1022
+ const answer = await ask(personaOf("roleplay/track-values"), brief$1(job, changed, tr, tr("The values that changed, to be given a new value:")), valuesSchema(changed), changed.length, "new values");
1023
+ let set = 0;
1024
+ const made = [];
1025
+ for (const item of changed) {
1026
+ const change = {
1027
+ key: item.key,
1028
+ to: answer[item.key]
1029
+ };
1030
+ if (change.to === void 0 || change.to === item.value) continue;
1031
+ try {
1032
+ job.store.story.edit({
1033
+ turn: job.turn,
1034
+ variableChanges: [{
1035
+ variable: item.variable.key,
1036
+ subject: item.subject.key,
1037
+ to: change.to
1038
+ }]
1039
+ });
1040
+ set += 1;
1041
+ made.push({
1042
+ key: item.key,
1043
+ from: shown(item.value),
1044
+ to: shown(change.to)
1045
+ });
1046
+ } catch (error) {
1047
+ deps.problem?.(`the tracked value ${item.key} of turn ${job.turn} was not set to ${shown(change.to)}: ${error instanceof Error ? error.message : String(error)}`);
1048
+ }
1049
+ }
1050
+ if (made.length > 0) try {
1051
+ job.store.recordTrace?.(job.turn, { tracked: made });
1052
+ } catch {}
1053
+ return set;
1054
+ } catch (error) {
1055
+ if (signal.aborted) throw error;
1056
+ deps.problem?.(`the tracked values of turn ${job.turn} could not be looked at: ${error instanceof Error ? error.message : String(error)}`);
1057
+ return 0;
1058
+ }
1059
+ } };
1060
+ }
1061
+ // src/host/decisions/errands.ts
1062
+ /** At most this many characters are asked about in one request, and the narration is cut to this many characters. */
1063
+ const MAX_ASKED = 6;
1064
+ const NARRATION_CHARS = 1500;
1065
+ const PROMPT = "roleplay/decide-errand";
1066
+ /** The characters a turn's words name that could be kept: awake, not the player's, and not already off their day. */
1067
+ function named(store, turn, text) {
1068
+ const lower = text.toLowerCase();
1069
+ return store.cast().flatMap((member) => {
1070
+ const { character } = member;
1071
+ if (character.control === "player" || character.kind !== "person" || store.asleep(turn, character.id) !== void 0) return [];
1072
+ if (store.agenda(turn, character.id).offDay !== void 0) return [];
1073
+ return [character.name, ...character.aliases ?? []].some((name) => name.trim() !== "" && lower.includes(name.toLowerCase())) ? [{
1074
+ id: character.id,
1075
+ key: member.key,
1076
+ name: character.name
1077
+ }] : [];
1078
+ }).slice(0, MAX_ASKED);
1079
+ }
1080
+ /**
1081
+ * After a turn, asks the decision model for each character the turn names whether the story told it, or it chose, to stay, wait or watch until the player's
1082
+ * character is with it again, and keeps those that did where they are. It is the harness's own look, so an errand given by the game master, by another
1083
+ * character or by the player is kept whoever gave it; the game master can also say so itself, with `waits_for_player` on an outcome.
1084
+ */
1085
+ function errandChecks(deps) {
1086
+ const seen = /* @__PURE__ */ new Map();
1087
+ return { async keep(job, signal) {
1088
+ const { store } = job;
1089
+ const settings = store.settings();
1090
+ if (settings.decisions.errands === "off" || !settings.schedule.enabled || store.holdForPlayer === void 0) return 0;
1091
+ const narration = job.narration.slice(0, NARRATION_CHARS);
1092
+ const candidates = named(store, job.turn, [
1093
+ job.input,
1094
+ narration,
1095
+ ...job.deeds
1096
+ ].join("\n"));
1097
+ if (candidates.length === 0) return 0;
1098
+ const asks = candidates.map((candidate) => ({
1099
+ key: candidate.key,
1100
+ instructions: store.text(PROMPT, { name: candidate.name })
1101
+ }));
1102
+ const { found, report } = await askExtra(deps.decisions?.(), {
1103
+ player_message: job.input,
1104
+ what_happened: job.deeds,
1105
+ what_the_player_read: narration
1106
+ }, asks, settings.decisions.gateThreshold, signal);
1107
+ noteExtra("errands", job.chat, store, report, seen, deps.problem);
1108
+ for (const key of found) store.holdForPlayer(candidates.find((candidate) => candidate.key === key).id);
1109
+ return found.length;
1110
+ } };
1111
+ }
756
1112
  // src/host/factions/strategist.ts
757
1113
  const LAST_KEY = "strategy.last";
758
1114
  const DAY_MS = 864e5;
@@ -1396,6 +1752,168 @@ var RollReplay = class {
1396
1752
  };
1397
1753
  }
1398
1754
  };
1755
+ // src/host/orchestration/autonomy.ts
1756
+ /** The longest message a character leaves: it is a note beside the story, not a scene. */
1757
+ const MAX_MESSAGE_CHARS = 500;
1758
+ const MINUTE$1 = 6e4;
1759
+ const seenProblems = /* @__PURE__ */ new Map();
1760
+ const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
1761
+ /** Whether a character could write to the player now: a person who knows the player, is awake, is not with them, and has not been asked lately. Higher is likelier. */
1762
+ function writingChance(store, member, player, turn, idleMs) {
1763
+ const { character } = member;
1764
+ if (character.control !== "agent" || character.kind !== "person" || character.tier === "background") return void 0;
1765
+ if (member.place !== void 0 && member.place.location.id === player.place?.location.id) return void 0;
1766
+ if (store.agenda(turn, character.id).now?.interruptible === false) return void 0;
1767
+ if (store.asleep(turn, character.id) !== void 0) return void 0;
1768
+ const relation = store.story.relationships.get(character.id, player.character.id);
1769
+ if (relation === void 0) return void 0;
1770
+ return clamp(.15 + .35 * clamp(relation.affinity, 0, 1) + .2 * Math.min(1, idleMs / (720 * MINUTE$1)), 0, .9);
1771
+ }
1772
+ /**
1773
+ * What the story does by itself while the player is away, once: the days of the characters are taken up to the real time (no model request), and, within
1774
+ * the limits of the chat, one character who is awake and knows the player may write to them. Nothing runs for a chat that has not switched it on, that
1775
+ * is not on the real clock, whose turn is being played, or that has done `maxUnanswered` things with no message from the player in between.
1776
+ */
1777
+ async function tickAutonomy(deps, chat, signal) {
1778
+ const store = deps.stores(chat);
1779
+ const autonomy = store?.autonomy;
1780
+ if (store === void 0 || autonomy === void 0) return {
1781
+ outcome: "off",
1782
+ moved: 0
1783
+ };
1784
+ const settings = store.settings();
1785
+ if (!settings.autonomy.enabled || settings.clock.mode !== "real") return {
1786
+ outcome: "off",
1787
+ moved: 0
1788
+ };
1789
+ if (deps.engine.playing(chat)) return {
1790
+ outcome: "busy",
1791
+ moved: 0
1792
+ };
1793
+ const turn = store.story.metadata.get().turns;
1794
+ const moved = autonomy.catchUp(turn).length;
1795
+ const shifted = autonomy.shifts();
1796
+ if (!settings.autonomy.messages) return {
1797
+ outcome: "quiet",
1798
+ moved
1799
+ };
1800
+ const config = settings.autonomy;
1801
+ const now = deps.wall();
1802
+ const state = autonomy.state();
1803
+ const last = autonomy.lastPlayerAt();
1804
+ if (state.unanswered >= config.maxUnanswered) return {
1805
+ outcome: "limit",
1806
+ moved
1807
+ };
1808
+ if (last === void 0 || now - last < config.idleMinutes * MINUTE$1) return {
1809
+ outcome: "recent",
1810
+ moved
1811
+ };
1812
+ if (now - last > config.awayHours * 60 * MINUTE$1) return {
1813
+ outcome: "away",
1814
+ moved
1815
+ };
1816
+ const cast = store.cast();
1817
+ const player = cast.find((member) => member.character.control === "player");
1818
+ if (player === void 0) return {
1819
+ outcome: "nobody",
1820
+ moved
1821
+ };
1822
+ const draw = deps.draw ?? seededRoll;
1823
+ const gap = config.messageGapMinutes * MINUTE$1;
1824
+ const eligible = cast.flatMap((member) => {
1825
+ if (now - (state.sent[member.key] ?? 0) < gap) return [];
1826
+ const chance = writingChance(store, member, player, turn, now - last);
1827
+ return chance === void 0 ? [] : [{
1828
+ member,
1829
+ chance
1830
+ }];
1831
+ });
1832
+ if (eligible.length === 0) return {
1833
+ outcome: "nobody",
1834
+ moved
1835
+ };
1836
+ const transition = eligible.filter((entry) => shifted.includes(entry.member.key) && draw(`${chat}:${entry.member.key}:shift:${now}`) < config.transitionChance);
1837
+ if (!(draw(`${chat}:look:${now}`) < config.chance * config.decay ** state.unanswered) && transition.length === 0) return {
1838
+ outcome: "idle",
1839
+ moved
1840
+ };
1841
+ const pool = transition.length > 0 ? transition : eligible;
1842
+ const total = pool.reduce((sum, entry) => sum + entry.chance, 0);
1843
+ let pick = draw(`${chat}:pick:${now}`) * total;
1844
+ const speaker = (pool.find((entry) => {
1845
+ pick -= entry.chance;
1846
+ return pick < 0;
1847
+ }) ?? pool[pool.length - 1]).member;
1848
+ const because = transition.some((entry) => entry.member === speaker);
1849
+ if (settings.decisions.messages === "on") {
1850
+ const time = store.time(turn);
1851
+ const asks = [{
1852
+ key: "write",
1853
+ instructions: store.text("roleplay/decide-message", {})
1854
+ }];
1855
+ const facts = {
1856
+ character: speaker.character.name,
1857
+ doing: store.agenda(turn, speaker.character.id).now?.activity ?? speaker.character.name,
1858
+ day_just_changed: because,
1859
+ hours_the_player_has_been_away: Math.round((now - last) / (60 * MINUTE$1) * 10) / 10,
1860
+ unanswered_messages: state.unanswered,
1861
+ time_of_day: describeInstant(time.now, time.zone)
1862
+ };
1863
+ const { found, report } = await askExtra(deps.decisions?.(), facts, asks, settings.decisions.gateThreshold, signal);
1864
+ noteExtra("messages", chat, store, report, seenProblems, deps.problem);
1865
+ if (report.problem === void 0 && found.length === 0) return {
1866
+ outcome: "declined",
1867
+ moved
1868
+ };
1869
+ }
1870
+ const parent = deps.agentOf(chat);
1871
+ if (parent === void 0) return {
1872
+ outcome: "off",
1873
+ moved
1874
+ };
1875
+ const language = languageOf(settings.prompts.language) === "zh" ? "zh" : "en";
1876
+ const tr = translator(language);
1877
+ const time = store.time(turn);
1878
+ const situation = [
1879
+ tr("The player's character has not been with you for {away}, and you are not with them now. It is {now} for you.", {
1880
+ away: describeDuration(now - last, language),
1881
+ now: describeInstant(time.now, time.zone, language)
1882
+ }),
1883
+ tr("You may write them a short message, in your own voice, as someone who knows them would: what you are doing, what is on your mind, something you want them to know or do. Say it in the utterance, in a line or two, with nothing around it."),
1884
+ because ? tr("Something in your own day has just changed, and it may have made you think of them.") : "",
1885
+ state.unanswered > 0 ? tr("You and others have already written to them since they were last here and they have not answered: do not press, and never complain about it.") : "",
1886
+ tr("If nothing makes you want to write now, answer with commitment low and no utterance.")
1887
+ ].filter((line) => line !== "").join(" ");
1888
+ const run = characterRunner({
1889
+ parent,
1890
+ boundaries: deps.boundaries,
1891
+ store
1892
+ });
1893
+ const report = await deps.engine.askAlone({
1894
+ chat,
1895
+ turn
1896
+ }, speaker.key, situation, run, signal);
1897
+ const text = report?.utterance?.trim().replace(/^["“「]|["”」]$/g, "").trim();
1898
+ if (report === void 0 || report.commitment === "low" || text === void 0 || text === "" || text.length > MAX_MESSAGE_CHARS || wrongLanguage(language, { message: text }, { strays: true }) !== void 0) {
1899
+ autonomy.asked(speaker.key, now);
1900
+ return {
1901
+ outcome: "quiet",
1902
+ moved
1903
+ };
1904
+ }
1905
+ autonomy.said(turn, {
1906
+ at: now,
1907
+ character: speaker.key,
1908
+ name: speaker.character.name,
1909
+ text
1910
+ });
1911
+ return {
1912
+ outcome: "wrote",
1913
+ moved,
1914
+ message: text
1915
+ };
1916
+ }
1399
1917
  // src/host/orchestration/check-tool.ts
1400
1918
  const CHECK_NARRATE_TOOL = "roll_and_narrate";
1401
1919
  const BRANCHES = [
@@ -1514,6 +2032,7 @@ function createCheckNarrateTool(deps) {
1514
2032
  if (check === void 0) throw new Error(`there is no check "${args.check}"; list_checks shows the story's checks`);
1515
2033
  const problem = deps.engine.soloCheckProblem(owner, args.character);
1516
2034
  if (problem !== void 0) throw new Error(problem);
2035
+ deps.engine.withoutPreview(owner);
1517
2036
  const given = {
1518
2037
  succeeded: args.on_success,
1519
2038
  partial: args.on_partial,
@@ -1688,7 +2207,7 @@ function rerankMemories(deps) {
1688
2207
  * someone to talk to, a way out, a thing to look at, then plain standbys. No model is asked.
1689
2208
  */
1690
2209
  function fallbackSuggestions(store, count) {
1691
- const tr = translator(languageOf(store.settings().prompts.language));
2210
+ const tr = translator(languageOf$1(store.settings().prompts.language));
1692
2211
  const player = store.cast().find((member) => member.character.control === "player");
1693
2212
  const view = player?.place === void 0 ? void 0 : store.place(player.place.location.id);
1694
2213
  const people = (view?.here ?? []).filter((member) => member.character.id !== player?.character.id).map((member) => tr("Talk to {name}.", { name: member.character.name }));
@@ -1727,10 +2246,14 @@ var AfterTurnJobs = class {
1727
2246
  judging = /* @__PURE__ */ new Set();
1728
2247
  reflecting = /* @__PURE__ */ new Set();
1729
2248
  casting = /* @__PURE__ */ new Set();
2249
+ tracking = /* @__PURE__ */ new Set();
2250
+ erranding = /* @__PURE__ */ new Set();
1730
2251
  constructor(deps) {
1731
2252
  this.deps = deps;
1732
2253
  }
1733
- start(owner, cancel) {
2254
+ start(owner, cancel, facts) {
2255
+ if (facts !== void 0) this.trackVariables(owner, cancel, facts);
2256
+ if (facts !== void 0) this.keepErrands(owner, cancel, facts);
1734
2257
  this.consolidate(owner, cancel);
1735
2258
  this.strategize(owner, cancel);
1736
2259
  this.judge(owner, cancel);
@@ -1738,6 +2261,42 @@ var AfterTurnJobs = class {
1738
2261
  const reason = this.reflectionDue(owner);
1739
2262
  if (reason !== void 0) this.reflect(owner, reason, cancel);
1740
2263
  }
2264
+ /** The values the story tracks are looked at once the turn is over, and set when what happened changed them. */
2265
+ trackVariables(owner, cancel, facts) {
2266
+ const store = this.deps.stores(owner.chat);
2267
+ if (store === void 0 || store.settings().decisions.variables === "off" || this.tracking.has(owner.chat)) return;
2268
+ this.tracking.add(owner.chat);
2269
+ this.deps.track(owner.chat, this.deps.boundaries().variableTracker.track({
2270
+ chat: owner.chat,
2271
+ turn: owner.turn,
2272
+ store,
2273
+ ...facts
2274
+ }, cancel).then((set) => {
2275
+ if (set > 0) this.deps.written(owner.chat);
2276
+ }).catch((error) => {
2277
+ if (!cancel.aborted) this.deps.problem(`the tracked values were not looked at: ${messageOf(error)}`);
2278
+ }).finally(() => {
2279
+ this.tracking.delete(owner.chat);
2280
+ }));
2281
+ }
2282
+ /** Characters the story told or left to wait for the player are kept where they are until the player comes to them. */
2283
+ keepErrands(owner, cancel, facts) {
2284
+ const store = this.deps.stores(owner.chat);
2285
+ if (store === void 0 || store.settings().decisions.errands === "off" || this.erranding.has(owner.chat)) return;
2286
+ this.erranding.add(owner.chat);
2287
+ this.deps.track(owner.chat, this.deps.boundaries().errandKeeper.keep({
2288
+ chat: owner.chat,
2289
+ turn: owner.turn,
2290
+ store,
2291
+ ...facts
2292
+ }, cancel).then((kept) => {
2293
+ if (kept > 0) this.deps.written(owner.chat);
2294
+ }).catch((error) => {
2295
+ if (!cancel.aborted) this.deps.problem(`who waits for the player was not looked at: ${messageOf(error)}`);
2296
+ }).finally(() => {
2297
+ this.erranding.delete(owner.chat);
2298
+ }));
2299
+ }
1741
2300
  /** Whether a reflection is running for the chat. */
1742
2301
  isReflecting(chat) {
1743
2302
  return this.reflecting.has(chat);
@@ -1966,7 +2525,7 @@ function explainPhase(state, attempted) {
1966
2525
  if (state.ooc !== void 0 && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character command: rule on it first with ooc_ruling" : state.ooc.ruling.legal ? "make the command happen with resolve_round, expand_world or advance_time, then call narrate with what the player perceives (narration only)" : "the command was refused: call narrate with no segments";
1967
2526
  const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
1968
2527
  switch (state.phase) {
1969
- case "idle": return judgeDue(state) ? "call judge_action first: does what the player's character tries work? It does not when it is not viable or it breaks a rule of the world or of the player" : previewDue(state) ? "call preview_scene first: two or three sentences that show the player how the scene opens, before the characters are asked" : state.judgement?.allowed === false && attempted !== "activate_characters" ? `the attempt does not work (${state.judgement.reason}): call resolve_round with one outcome, for the player's character only (result failed, a sentence on what it does and why nothing comes of it)${attempted === "narrate" ? ", then narrate" : ""}` : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : attempted === "narrate" ? "nothing to deliver yet: call activate_characters to let the characters act, or, when nobody else needs to react, call resolve_round with an outcome for the player's character alone, and then narrate" : "nothing to resolve yet: call activate_characters first";
2528
+ case "idle": return state.dreaming !== void 0 && attempted !== "resolve_round" ? `this turn is a dream, not an out-of-character command: call activate_characters with only ${state.dreaming} (the sleeper stays asleep), then narrate the dream` : judgeDue(state) ? "call judge_action first: does what the player's character tries work? It does not when it is not viable or it breaks a rule of the world or of the player" : previewDue(state) ? "call preview_scene first: two or three sentences that show the player how the scene opens, before the characters are asked" : state.judgement?.allowed === false && attempted !== "activate_characters" ? `the attempt does not work (${state.judgement.reason}): call resolve_round with one outcome, for the player's character only (result failed, a sentence on what it does and why nothing comes of it)${attempted === "narrate" ? ", then narrate" : ""}` : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : attempted === "narrate" ? "nothing to deliver yet: call activate_characters to let the characters act, or, when nobody else needs to react, call resolve_round with an outcome for the player's character alone, and then narrate" : "nothing to resolve yet: call activate_characters first";
1970
2529
  case "resolving": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round with one outcome for each of: ${waiting(state.first)}` : `call resolve_round with one outcome for each of: ${waiting(state.first)}`;
1971
2530
  case "retrying": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round once more, with one outcome for each of: ${waiting(state.second)}` : `call resolve_round once more, with one outcome for each of: ${waiting(state.second)}`;
1972
2531
  case "between": return attempted === "resolve_round" ? "the round is already recorded: call activate_characters again if the story needs it, or narrate" : `call narrate with the output of the turn${mustSay(state)}${canContinue(state)}`;
@@ -1999,9 +2558,23 @@ function checkOutcomes(attempt, outcomes, store, player, decreed, state) {
1999
2558
  ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`)),
2000
2559
  ...state === void 0 ? [] : rollProblems(outcomes, store, state)
2001
2560
  ];
2002
- if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} (expected exactly: ${expected.join(", ")})`);
2561
+ if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} ${expected.length === 0 ? "" : ` (expected exactly: ${expected.join(", ")})`}`);
2003
2562
  for (const outcome of outcomes) if (outcome.roll !== void 0) state?.cited.add(outcome.roll);
2004
2563
  }
2564
+ /** An outcome that gives a rolled-for character the dice's own result but leaves out the citation is mended, not refused: the model was seen to resend the same call nine times while naming the missing field. */
2565
+ function mendRolls(outcomes, store, state) {
2566
+ if (outcomes.every((outcome) => outcome.roll !== void 0)) return outcomes;
2567
+ const open = store.story.dice.rolls({ turn: state.turn }).filter((roll) => roll.readout !== void 0 && roll.character !== void 0 && !state.cited.has(roll.id) && !outcomes.some((outcome) => outcome.roll === roll.id));
2568
+ return outcomes.map((outcome) => {
2569
+ if (outcome.roll !== void 0) return outcome;
2570
+ const own = open.filter((roll) => roll.character === outcome.character);
2571
+ const [only] = own;
2572
+ return own.length === 1 && only?.readout?.result === outcome.result ? {
2573
+ ...outcome,
2574
+ roll: only.id
2575
+ } : outcome;
2576
+ });
2577
+ }
2005
2578
  /**
2006
2579
  * Why an outcome does not follow the dice, if it does not. A roll decides what it was rolled for: the result of the outcome is the roll's own, a roll serves one outcome,
2007
2580
  * and a character a check was rolled for cannot be given an outcome without it.
@@ -2155,6 +2728,7 @@ async function askCharacters(deps, owner, number, keys, cast, state, run, signal
2155
2728
  text: (id, variables) => deps.storeOf(owner).text(id, variables),
2156
2729
  ...time === void 0 ? {} : { time },
2157
2730
  ...agenda === void 0 ? {} : { agenda },
2731
+ ...state.dreaming === key ? { dreaming: true } : {},
2158
2732
  ...cues.length === 0 ? {} : { cues },
2159
2733
  ...upcoming.length === 0 ? {} : { upcoming },
2160
2734
  ...tracked === void 0 || tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
@@ -2208,6 +2782,13 @@ async function askCharacters(deps, owner, number, keys, cast, state, run, signal
2208
2782
  };
2209
2783
  }
2210
2784
  // src/host/orchestration/round-record.ts
2785
+ /** Whether what happened to a character takes it off its routine: it went somewhere because of it, it was asleep (a dreamer stays asleep) and has been woken, or the game master said so. */
2786
+ function holds(member, outcome, check, state, store, turn) {
2787
+ if (member.character.control === "player") return false;
2788
+ if (outcome.offRoutineMinutes !== void 0 || outcome.waitsForPlayer === true) return true;
2789
+ if (check?.ok === true && check.plan.from !== check.move.to) return true;
2790
+ return state.dreaming !== member.key && store.asleep(turn, member.character.id) !== void 0;
2791
+ }
2211
2792
  /** Records the game master's decisions as a finished round: what the characters did and said, what changed in the story, and the round queued for the keeper. `fire` runs the triggers the round may have made true. */
2212
2793
  function recordRound(store, owner, state, fire) {
2213
2794
  const decided = decisions(state);
@@ -2254,6 +2835,10 @@ function recordRound(store, owner, state, fire) {
2254
2835
  ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() }
2255
2836
  },
2256
2837
  ...check?.ok === true ? { move: check.move } : {},
2838
+ ...holds(member, outcome, check, state, store, owner.turn) ? { hold: {
2839
+ ...outcome.offRoutineMinutes === void 0 ? {} : { minutes: outcome.offRoutineMinutes },
2840
+ ...outcome.waitsForPlayer === true ? { untilPlayer: true } : {}
2841
+ } } : {},
2257
2842
  ...outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 ? {} : { items: outcome.itemChanges }
2258
2843
  }
2259
2844
  }];
@@ -2531,7 +3116,30 @@ function asSpoken(segments, spoken) {
2531
3116
  * The output the game master delivered, once it is acceptable: every utterance exactly once and in order, and the narration in the chat's language.
2532
3117
  * A refusal is thrown for the game master to correct; past `MAX_REFUSALS`, or when `silent`, the output is repaired instead.
2533
3118
  */
2534
- function checkedOutput(narrationChecker, language, state, segments, silent) {
3119
+ /** The narration of the output without the status bars and panels a game master wrote into it: the story shows its tracked values itself. Utterances are never touched. */
3120
+ function withoutPanels(segments) {
3121
+ let found = false;
3122
+ return {
3123
+ segments: segments.flatMap((segment) => {
3124
+ if (segment.type !== "narration") return [segment];
3125
+ const { prose, panels } = splitPanels(segment.text, { alone: true });
3126
+ if (panels.length === 0) return [segment];
3127
+ found = true;
3128
+ return prose === "" ? [] : [{
3129
+ ...segment,
3130
+ text: prose
3131
+ }];
3132
+ }),
3133
+ found
3134
+ };
3135
+ }
3136
+ function checkedOutput(narrationChecker, language, state, delivered, silent) {
3137
+ const cleaned = withoutPanels(delivered);
3138
+ if (cleaned.found && !silent && state.refused < 2) {
3139
+ state.refused += 1;
3140
+ throw new Error("the output is not acceptable: the narration holds a status bar, panel or block of tags. The story shows its tracked values itself, so write only the story. Deliver it again without it; utterances may not be touched");
3141
+ }
3142
+ const segments = cleaned.segments;
2535
3143
  const problems = [...segments.flatMap((segment, index) => segment.type === "utterance" && segment.character === "" ? [`segment ${index + 1}: an utterance needs the character who says it`] : []), ...narrationChecker.check(segments, state.utterances)];
2536
3144
  const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") }, { strays: true });
2537
3145
  if (problems.length === 0 && wording !== void 0 && !silent && state.refused < 2) {
@@ -2540,7 +3148,7 @@ function checkedOutput(narrationChecker, language, state, segments, silent) {
2540
3148
  }
2541
3149
  if (problems.length === 0) return {
2542
3150
  segments: asSpoken(segments, state.utterances),
2543
- repaired: false
3151
+ repaired: cleaned.found
2544
3152
  };
2545
3153
  state.refused += 1;
2546
3154
  if (!silent && state.refused <= 2) throw new Error(`the output is not acceptable: ${problems.join("; ")}. Deliver it again with these corrected; narration may be written freely, utterances may not be touched`);
@@ -2606,7 +3214,10 @@ async function runOffScene(deps, owner, state, store, due, limit) {
2606
3214
  return member === void 0 ? [] : [{
2607
3215
  character: member.character.id,
2608
3216
  patch: { activity: report.intent },
2609
- ...move?.ok === true ? { move: move.move } : {}
3217
+ ...move?.ok === true ? {
3218
+ move: move.move,
3219
+ hold: {}
3220
+ } : {}
2610
3221
  }];
2611
3222
  }));
2612
3223
  state.offstage += 1;
@@ -2649,7 +3260,11 @@ async function runOffScene(deps, owner, state, store, due, limit) {
2649
3260
  }
2650
3261
  }
2651
3262
  // src/host/orchestration/turn-engine.ts
3263
+ /** Asks one character to act; what the game master calls a character is the character's key. */
3264
+ /** Told to the game master when it asks again in a dream the harness has already asked. */
3265
+ const DREAM_ASKED = "the sleeper was already asked for this dream and nothing in a dream changes the waking world: call narrate with the dream, as narration only";
2652
3266
  const MAX_OBJECTIONS = 3;
3267
+ const MAX_PREVIEW_REFUSALS = 3;
2653
3268
  /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
2654
3269
  const MAX_ROUND_SECONDS = 86400;
2655
3270
  /** The runs of the record keeper that may fail one after another before the rounds waiting for it are given up, so that they cannot pile up for ever. */
@@ -2682,6 +3297,8 @@ var TurnEngine = class {
2682
3297
  reflectionCancels = /* @__PURE__ */ new Map();
2683
3298
  /** Chats whose characters away from the player are being asked about what fell due: one run at a time. */
2684
3299
  offstage = /* @__PURE__ */ new Set();
3300
+ /** Told when a round of characters begins; the function it returns is told how the round went. Used to trace rounds, never to decide anything. */
3301
+ observe;
2685
3302
  constructor(boundaries, stores, problem = () => void 0, written = () => void 0) {
2686
3303
  this.boundaries = boundaries;
2687
3304
  this.stores = stores;
@@ -2705,6 +3322,30 @@ var TurnEngine = class {
2705
3322
  * The turn is an out-of-character command of the player: nobody is asked to act and no preview is shown. The game master rules on
2706
3323
  * whether it is allowed (`rule`) and, if so, makes it happen with outcomes for any characters, with the world's tools, and says what the player perceives.
2707
3324
  */
3325
+ /** The turn is the player's visit to the dream of a sleeping character: the sleeper may be asked, and stays asleep. */
3326
+ beginDream(owner, key, situation) {
3327
+ const state = this.stateFor(owner);
3328
+ state.dreaming = key;
3329
+ state.dreamSituation = situation;
3330
+ }
3331
+ /**
3332
+ * The harness asks the sleeper itself, so that a dream never depends on the game master choosing the right tools: the answer is
3333
+ * returned for the game master to narrate and no round is recorded, because nothing in a dream changes the waking world.
3334
+ * Nothing is returned when the sleeper could not answer, and the game master then asks as in any turn.
3335
+ */
3336
+ async dream(owner, run) {
3337
+ const state = this.stateFor(owner);
3338
+ const key = state.dreaming;
3339
+ if (key === void 0) return void 0;
3340
+ const store = this.storeOf(owner);
3341
+ state.situation = state.dreamSituation ?? "";
3342
+ state.cast = store.cast();
3343
+ const report = (await this.ask(owner, 1, [key], state.cast, state, run, state.cancel.signal)).reports[0];
3344
+ if (report === void 0) return void 0;
3345
+ state.dreamed = true;
3346
+ state.phase = "between";
3347
+ return report;
3348
+ }
2708
3349
  beginOoc(owner, request, question = false) {
2709
3350
  const state = this.stateFor(owner);
2710
3351
  state.ooc = {
@@ -2760,7 +3401,7 @@ var TurnEngine = class {
2760
3401
  * When the action is said to happen at a place (`at`, a place key) and the character is somewhere else, it does not work whatever was judged: the character has to get there first.
2761
3402
  * @throws {Error} when the turn is not an ordinary one, was already judged, the reason is empty, or `at` is not a place.
2762
3403
  */
2763
- judge(owner, allowed, reason, at, uncertain) {
3404
+ judge(owner, allowed, reason, at, uncertain, goesTo) {
2764
3405
  const state = this.stateFor(owner);
2765
3406
  if (state.ooc !== void 0) throw new Error("this turn is an out-of-character " + (state.ooc.question === true ? "question: answer it with ooc_answer" : "command: rule on it with ooc_ruling"));
2766
3407
  if (state.phase !== "idle") throw new Error("the action is judged first, before anything else");
@@ -2785,9 +3426,16 @@ var TurnEngine = class {
2785
3426
  };
2786
3427
  }
2787
3428
  }
3429
+ const destination = goesTo?.trim() ?? "";
3430
+ if (destination !== "") {
3431
+ const store = this.storeOf(owner);
3432
+ const player = store.cast().find((member) => member.character.control === "player");
3433
+ if (whereabouts(store.story.locations.list(), player?.place?.location, destination).kind === "unknown") throw new Error(`there is no place "${destination}" (list_locations shows the keys): name the place the character is going to, or leave "goes_to" out`);
3434
+ }
2788
3435
  state.judgement = {
2789
3436
  allowed,
2790
- reason: why
3437
+ reason: why,
3438
+ ...allowed && destination !== "" ? { goesTo: destination } : {}
2791
3439
  };
2792
3440
  const { tools } = this.storeOf(owner).settings();
2793
3441
  if (allowed && uncertain === true && (toolEnabled(tools, "gameMaster", "roll_check") || toolEnabled(tools, "gameMaster", "roll_dice"))) {
@@ -2838,11 +3486,12 @@ var TurnEngine = class {
2838
3486
  */
2839
3487
  async activate(owner, input, run, signal) {
2840
3488
  const state = this.stateFor(owner);
3489
+ if (state.dreamed === true) throw new Error(DREAM_ASKED);
2841
3490
  if (state.ooc !== void 0) throw new Error(state.ooc.question === true ? "a question asks nobody to act and changes nothing: answer it with ooc_answer" : "an out-of-character command asks nobody to act: decree what happens with resolve_round, or narrate");
2842
3491
  if (state.phase !== "idle" && state.phase !== "between") throw new Error(explainPhase(state, "activate_characters"));
2843
3492
  if (judgeDue(state)) throw new Error(explainPhase(state, "activate_characters"));
2844
3493
  if (state.judgement?.allowed === false && state.rounds === 0) throw new Error(`the action cannot work (${state.judgement.reason}): nobody is asked to act on it. Play the failed attempt with resolve_round: one outcome for the player's character, result failed`);
2845
- if (previewDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3494
+ if (this.previewHeld(state)) throw new Error(explainPhase(state, "activate_characters"));
2846
3495
  if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
2847
3496
  const store = this.storeOf(owner);
2848
3497
  const limit = store.settings().maxRounds;
@@ -2851,11 +3500,25 @@ var TurnEngine = class {
2851
3500
  if (situation === "") throw new Error("describe the situation: the characters are told nothing else");
2852
3501
  const cast = store.cast();
2853
3502
  const most = store.settings().maxCharacters;
2854
- const keys = this.boundaries().planner.plan({
3503
+ const planned = this.boundaries().planner.plan({
2855
3504
  cast,
2856
3505
  ...input.characters === void 0 ? {} : { requested: input.characters }
2857
3506
  });
2858
- if (keys.length === 0) throw new Error("there is no character to activate");
3507
+ const sleeping = planned.flatMap((key) => {
3508
+ const member = cast.find((candidate) => candidate.key === key);
3509
+ const asleep = member === void 0 || state.dreaming === key ? void 0 : store.asleep(owner.turn, member.character.id);
3510
+ return asleep === void 0 ? [] : [{
3511
+ key,
3512
+ name: member.character.name,
3513
+ until: asleep.until
3514
+ }];
3515
+ });
3516
+ const woken = sleeping.filter((entry) => input.wakes?.includes(entry.key) === true);
3517
+ const sleepers = sleeping.filter((entry) => !woken.includes(entry));
3518
+ if (sleepers.length > 0 && input.characters !== void 0 && input.characters.length > 0) throw new Error(`${sleepers.map((entry) => entry.name).join(", ")} ${sleepers.length === 1 ? "is" : "are"} asleep: asleep characters take part only if what the player does wakes them. If it does, name them in wakes and show them waking in your narration; otherwise leave them out`);
3519
+ const keys = planned.filter((key) => !sleepers.some((entry) => entry.key === key));
3520
+ if (keys.length === 0) throw new Error(sleepers.length > 0 ? `${sleepers.map((entry) => entry.name).join(", ")} ${sleepers.length === 1 ? "is" : "are"} asleep, so nobody here can act: narrate the quiet, or wake them with wakes` : "there is no character to activate");
3521
+ if (woken.length > 0) state.woken = /* @__PURE__ */ new Set([...state.woken ?? [], ...woken.map((entry) => entry.key)]);
2859
3522
  if (keys.length > most) throw new Error(`${keys.length} characters were asked, which is more than one round allows (${most}): ask only those the moment actually reaches, and the others in a later round if the story comes to them`);
2860
3523
  const signature = `${[...keys].sort((a, b) => a.localeCompare(b)).join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
2861
3524
  if (repeatsEarlier(signature, state.asked)) throw new Error("the same characters were already asked about the same situation in this message, so nothing new would come of it: say what changed, ask others, or deliver the output with narrate");
@@ -2888,9 +3551,11 @@ var TurnEngine = class {
2888
3551
  async resolve(owner, outcomes, run, signal, elapsedSeconds) {
2889
3552
  const state = this.stateFor(owner);
2890
3553
  const store = this.storeOf(owner);
3554
+ if (state.dreamed === true) throw new Error(DREAM_ASKED);
3555
+ outcomes = mendRolls(outcomes, store, state);
2891
3556
  if (state.ooc !== void 0) return { done: this.decree(owner, state, outcomes, elapsedSeconds) };
2892
3557
  if (state.phase === "idle" || state.phase === "between") {
2893
- if (judgeDue(state) || previewDue(state)) throw new Error(explainPhase(state, "resolve_round"));
3558
+ if (judgeDue(state) || this.previewHeld(state)) throw new Error(explainPhase(state, "resolve_round"));
2894
3559
  if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
2895
3560
  const player = store.cast().find((member) => member.character.control === "player");
2896
3561
  if (player !== void 0 && outcomes.length === 1 && outcomes[0]?.character === player.key) return { done: this.resolvePlayer(owner, state, outcomes[0], elapsedSeconds) };
@@ -2959,13 +3624,25 @@ var TurnEngine = class {
2959
3624
  };
2960
3625
  return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
2961
3626
  }
3627
+ /** The preview comes first, but a game master that does not show it must not go on refused for ever (a model repeated the same refused calls for the rest of the turn): after a few refusals it is let go and the turn goes on without one. */
3628
+ previewHeld(state) {
3629
+ if (!previewDue(state)) return false;
3630
+ state.previewRefusals += 1;
3631
+ if (state.previewRefusals <= MAX_PREVIEW_REFUSALS) return true;
3632
+ state.previewWanted = false;
3633
+ return false;
3634
+ }
3635
+ /** The turn settles a lone attempt in one step: nobody is asked to act, so there is no scene to preview. */
3636
+ withoutPreview(owner) {
3637
+ this.stateFor(owner).previewWanted = false;
3638
+ }
2962
3639
  /** Why a lone check of the player's character cannot be rolled, recorded and narrated in one call, if it cannot: nothing is rolled until this is clear. */
2963
3640
  soloCheckProblem(owner, character) {
2964
3641
  const state = this.stateFor(owner);
2965
3642
  const store = this.storeOf(owner);
2966
3643
  if (state.ooc !== void 0) return "this turn is an out-of-character one: use ooc_ruling or ooc_answer";
2967
3644
  if (state.phase !== "idle" || state.rounds > 0) return "characters were already played in this turn: roll with roll_check, decide with resolve_round and deliver with narrate";
2968
- if (judgeDue(state) || previewDue(state)) return explainPhase(state, "resolve_round");
3645
+ if (judgeDue(state)) return explainPhase(state, "resolve_round");
2969
3646
  if (state.judgement?.allowed === false) return `the action cannot work (${state.judgement.reason}): play it as a failed attempt with resolve_round, then narrate`;
2970
3647
  const player = store.cast().find((member) => member.character.control === "player");
2971
3648
  return player?.key === character ? void 0 : `this is only for the player's character${player === void 0 ? "" : ` (${player.key})`}: anyone else's attempt goes through activate_characters`;
@@ -3065,11 +3742,13 @@ var TurnEngine = class {
3065
3742
  */
3066
3743
  async narrate(owner, segments, run, addressed = []) {
3067
3744
  const state = this.stateFor(owner);
3745
+ if (state.phase === "idle") this.previewHeld(state);
3068
3746
  if (state.phase !== "between") throw new Error(explainPhase(state, "narrate"));
3069
3747
  const pending = new Set(this.storeOf(owner).pendingBeats().map((beat) => beat.id));
3070
3748
  const unknown = addressed.filter((id) => !pending.has(id));
3071
3749
  if (unknown.length > 0) throw new Error(`addressed: ${unknown.join(", ")} ${unknown.length === 1 ? "is" : "are"} not ${unknown.length === 1 ? "a beat" : "beats"} still to weave in (the scene lists them)`);
3072
3750
  state.addressed = [...new Set(addressed)];
3751
+ if (state.dreamed === true && segments.some((segment) => segment.type === "utterance")) throw new Error("a dream is narrated, and what the sleeper says in it is part of the narration: deliver narration segments only");
3073
3752
  if (state.ooc !== void 0) {
3074
3753
  if (state.ooc.question === true && segments.length > 0) throw new Error("a question is answered with ooc_answer: deliver no segments, the player is shown the answer");
3075
3754
  if (state.ooc.ruling?.legal !== true && segments.length > 0) throw new Error("the command was refused: deliver no segments, the player is told why");
@@ -3105,7 +3784,9 @@ var TurnEngine = class {
3105
3784
  * story genuinely needs it, and makes it or says why not. @throws {Error} when the world is closed, the turn's limit is reached or a round is open.
3106
3785
  */
3107
3786
  async expand(owner, input, signal) {
3108
- return await expandWorld(this.boundaries(), this.storeOf(owner), this.stateFor(owner), owner, input, signal);
3787
+ const state = this.stateFor(owner);
3788
+ if (state.dreaming !== void 0) throw new Error(`this turn is a dream: nothing is made up for it and the world is not changed. Call activate_characters with only ${state.dreaming} (the sleeper stays asleep), then narrate the dream`);
3789
+ return await expandWorld(this.boundaries(), this.storeOf(owner), state, owner, input, signal);
3109
3790
  }
3110
3791
  /** The game master introduces a thing the story uses, with no world author asked. @throws {Error} when the world is closed, a round is open, or the thing cannot be put where it was said. */
3111
3792
  introduce(owner, input) {
@@ -3273,9 +3954,11 @@ var TurnEngine = class {
3273
3954
  }
3274
3955
  /**
3275
3956
  * Whether the game master may still be turned back, counting this objection. Only objections that get nowhere count: a turn that has moved on since the
3276
- * last one (what is missing changed) starts the count again, because a turn cut short by a model's output limit has to be steered through every step.
3957
+ * last one (what is missing changed) starts the count again, because a turn cut short by a model's output limit has to be steered through every step. A step that
3958
+ * made tool calls (`progressing`) is not an objection that gets nowhere and is not counted.
3277
3959
  */
3278
- object(owner, missing) {
3960
+ object(owner, missing, progressing = false) {
3961
+ if (progressing) return true;
3279
3962
  const key = `${owner.chat}#${owner.turn}`;
3280
3963
  const last = this.objections.get(key);
3281
3964
  const count = last?.missing === missing ? last.count + 1 : 1;
@@ -3323,7 +4006,12 @@ var TurnEngine = class {
3323
4006
  stateFor({ chat, turn }) {
3324
4007
  const known = this.states.get(chat);
3325
4008
  if (known?.turn === turn) return known;
3326
- const fresh = {
4009
+ const fresh = this.blankState(chat, turn);
4010
+ this.states.set(chat, fresh);
4011
+ return fresh;
4012
+ }
4013
+ blankState(chat, turn) {
4014
+ return {
3327
4015
  turn,
3328
4016
  phase: "idle",
3329
4017
  cast: [],
@@ -3339,6 +4027,7 @@ var TurnEngine = class {
3339
4027
  reported: /* @__PURE__ */ new Set(),
3340
4028
  refused: 0,
3341
4029
  previewed: false,
4030
+ previewRefusals: 0,
3342
4031
  previewWanted: this.stores(chat)?.settings().preview.enabled ?? false,
3343
4032
  focus: [],
3344
4033
  requested: false,
@@ -3348,8 +4037,16 @@ var TurnEngine = class {
3348
4037
  cues: /* @__PURE__ */ new Map(),
3349
4038
  addressed: []
3350
4039
  };
3351
- this.states.set(chat, fresh);
3352
- return fresh;
4040
+ }
4041
+ /**
4042
+ * One character, asked alone about a situation of its own, away from any turn (the player is not playing): what it answers is returned and nothing else is
4043
+ * recorded, so a message can be written while the player is away. The turn is only the one the story is at, for what the character remembers and knows.
4044
+ */
4045
+ async askAlone(owner, key, situation, run, signal) {
4046
+ const store = this.storeOf(owner);
4047
+ const state = this.blankState(owner.chat, owner.turn);
4048
+ state.situation = situation;
4049
+ return (await this.ask(owner, 1, [key], store.cast(), state, run, signal, true)).reports[0];
3353
4050
  }
3354
4051
  storeOf(owner) {
3355
4052
  const store = this.stores(owner.chat);
@@ -3357,7 +4054,13 @@ var TurnEngine = class {
3357
4054
  return store;
3358
4055
  }
3359
4056
  ask(owner, number, keys, cast, state, run, signal, away = false) {
3360
- return askCharacters({
4057
+ const done = this.observe?.(owner.chat, {
4058
+ turn: owner.turn,
4059
+ attempt: number,
4060
+ characters: keys,
4061
+ away
4062
+ });
4063
+ const asked = askCharacters({
3361
4064
  boundaries: this.boundaries(),
3362
4065
  store: this.stores(owner.chat),
3363
4066
  storeOf: (o) => this.storeOf(o),
@@ -3365,6 +4068,14 @@ var TurnEngine = class {
3365
4068
  this.problem(message);
3366
4069
  }
3367
4070
  }, owner, number, keys, cast, state, run, signal, away);
4071
+ if (done === void 0) return asked;
4072
+ return asked.then((attempt) => {
4073
+ done(attempt);
4074
+ return attempt;
4075
+ }, (error) => {
4076
+ done(error instanceof Error ? error : new Error(String(error)));
4077
+ throw error;
4078
+ });
3368
4079
  }
3369
4080
  /**
3370
4081
  * The game master asks for what happened to be written into the story's lasting records. The memory
@@ -3492,8 +4203,24 @@ var TurnEngine = class {
3492
4203
  state.refused += 1;
3493
4204
  throw new Error(`the output is not acceptable: ${findings.map((finding) => finding.message).join("; ")}. Deliver it again with this corrected; utterances may not be touched`);
3494
4205
  }
4206
+ /**
4207
+ * The player's character was judged to be going somewhere, and the story still has it where it was: the output is sent back once, because
4208
+ * a move that is only narrated is not recorded (the next turn would start from the old place). If something stopped the character, the second delivery stands.
4209
+ */
4210
+ checkArrival(owner, state, silent) {
4211
+ const goesTo = state.judgement?.goesTo;
4212
+ if (goesTo === void 0 || silent || state.arrivalChecked === true || state.ooc !== void 0) return;
4213
+ const store = this.storeOf(owner);
4214
+ const player = store.cast().find((member) => member.character.control === "player");
4215
+ if (player?.place === void 0) return;
4216
+ const found = whereabouts(store.story.locations.list(), player.place.location, goesTo);
4217
+ if (found.kind !== "elsewhere") return;
4218
+ state.arrivalChecked = true;
4219
+ throw new Error(`${player.character.name} was judged to be going to ${found.target.name}, but is still at ${found.here.name} in the story's records, and what is not recorded did not happen: record the move with resolve_round (an outcome for ${player.character.name} with moves_to ${goesTo}), then narrate again. If something stops ${player.character.name} on the way, deliver the narration again as it is and say what stopped them`);
4220
+ }
3495
4221
  async deliver(owner, state, segments, silent, run) {
3496
4222
  let output = checkedOutput(this.boundaries().narrationChecker, this.storeOf(owner).settings().prompts.language, state, segments, silent);
4223
+ this.checkArrival(owner, state, silent);
3497
4224
  await this.gate(owner, state, output, silent);
3498
4225
  if (state.ooc?.ruling !== void 0) output = {
3499
4226
  ...output,
@@ -3511,7 +4238,11 @@ var TurnEngine = class {
3511
4238
  this.suggestAfter(owner, state, output);
3512
4239
  this.startDueWrite(owner, state);
3513
4240
  this.delivered.set(owner.chat, state);
3514
- this.afterTurn.start(owner, state.cancel.signal);
4241
+ this.afterTurn.start(owner, state.cancel.signal, {
4242
+ input: state.input ?? "",
4243
+ deeds: state.history.flatMap((entry) => [`${entry.name}: ${entry.summary}`, ...entry.utterance === void 0 ? [] : [`${entry.name}: "${entry.utterance}"`]]),
4244
+ narration: output.segments.map((segment) => segment.type === "narration" ? segment.text : `${segment.name}: ${segment.text}`).join("\n")
4245
+ });
3515
4246
  if (run !== void 0) this.offSceneIfDue(owner, state, run);
3516
4247
  return output;
3517
4248
  }
@@ -3580,7 +4311,7 @@ var ImageJobs = class {
3580
4311
  this.failures.delete(this.key(id, node));
3581
4312
  const request = output.segments.map((segment) => segment.type === "utterance" ? `${segment.name}: “${segment.text}”` : segment.text).join("\n");
3582
4313
  const reuse = automatic && settings.images.reuse;
3583
- const present = () => (this.deps.presenter ?? runImagePresenter)({
4314
+ const present$1 = () => (this.deps.presenter ?? runImagePresenter)({
3584
4315
  parent,
3585
4316
  signal: controller.signal,
3586
4317
  service: withPriority(service, priority, settings.images.highRes),
@@ -3598,7 +4329,27 @@ var ImageJobs = class {
3598
4329
  ...reuse && this.deps.embedder?.() !== void 0 ? { embedder: this.deps.embedder() } : {},
3599
4330
  ...settings.reasoning.children === "" ? {} : { reasoningEffort: settings.reasoning.children }
3600
4331
  });
3601
- const promise = (reuse && settings.images.interpret && this.deps.attachments?.() !== void 0 ? this.describePending(id, controller.signal).then(present) : present()).then(() => void 0).catch((error) => {
4332
+ const store = () => this.deps.turnStore?.(chatSessionId(id));
4333
+ const begin = () => {
4334
+ const make = () => reuse && settings.images.interpret && this.deps.attachments?.() !== void 0 ? this.describePending(id, controller.signal).then(present$1) : present$1();
4335
+ const waiting = this.deps.beforeGeneration?.(chatSessionId(id), controller.signal);
4336
+ return waiting === void 0 ? make() : waiting.then(make);
4337
+ };
4338
+ const makeOrShow = async () => {
4339
+ const turns = store();
4340
+ const picked = automatic && reuse && turns !== void 0 && this.deps.reuseExisting !== void 0 ? await this.deps.reuseExisting({
4341
+ chat: chatSessionId(id),
4342
+ store: turns,
4343
+ root: sessionFolder(this.deps.sessionsDir(), id),
4344
+ moment: request
4345
+ }, controller.signal) : void 0;
4346
+ if (picked === void 0) return await begin();
4347
+ await present(sessionFolder(this.deps.sessionsDir(), id), node, {
4348
+ path: picked,
4349
+ reason: "a stored picture that shows this moment"
4350
+ });
4351
+ };
4352
+ const promise = makeOrShow().then(() => void 0).catch((error) => {
3602
4353
  if (controller.signal.aborted) return;
3603
4354
  const message = error instanceof Error ? error.message : String(error);
3604
4355
  this.failures.set(this.key(id, node), message);
@@ -3735,6 +4486,38 @@ var ImageJobs = class {
3735
4486
  return `${id}/${node}`;
3736
4487
  }
3737
4488
  };
4489
+ // src/host/images/reuse.ts
4490
+ /** How many close candidates are put to the decision model, and how much of the moment it is shown. */
4491
+ const CANDIDATES = 6;
4492
+ const MOMENT_CHARS = 1500;
4493
+ /**
4494
+ * Looks for a stored picture that shows the moment, before one is made (`decisions.reuse`): the close candidates by words and meaning, each put to the decision model with its description,
4495
+ * the first it says fits taken. A picture of the same place at another moment, or with something else in it, is what the decision model is told to refuse. Nothing is found without a
4496
+ * decision model; a failure is reported once and a picture is made as before.
4497
+ * @returns the path of the picture to show again, if there is one.
4498
+ */
4499
+ function pictureReuse(deps) {
4500
+ const seen = /* @__PURE__ */ new Map();
4501
+ return async (job, signal) => {
4502
+ const settings = job.store.settings();
4503
+ if (settings.decisions.reuse === "off") return void 0;
4504
+ const stored = (await listGallery(job.root)).filter((image) => image.reusable && image.pending !== true && (image.description ?? "").trim() !== "");
4505
+ if (stored.length === 0) return void 0;
4506
+ const { matches } = await findImages(job.root, stored, {
4507
+ text: job.moment,
4508
+ limit: CANDIDATES
4509
+ }, deps.embedder?.(), signal);
4510
+ if (matches.length === 0) return void 0;
4511
+ const asks = matches.map(({ image }, index) => ({
4512
+ key: `picture${index}`,
4513
+ instructions: job.store.text("roleplay/decide-reuse", { description: image.description.trim() })
4514
+ }));
4515
+ const { found, report } = await askExtra(deps.decisions?.(), { moment: job.moment.slice(0, MOMENT_CHARS) }, asks, settings.decisions.reuseThreshold, signal);
4516
+ noteExtra("reuse", job.chat, job.store, report, seen, deps.problem);
4517
+ const first = found[0];
4518
+ return first === void 0 ? void 0 : matches[Number(first.slice(7))].image.path;
4519
+ };
4520
+ }
3738
4521
  // src/orchestration.ts
3739
4522
  const WORKING_DIRECTORY_CONTEXT = "working-directory:current";
3740
4523
  const name = "@dsh-agentic-roleplay/core/orchestration";
@@ -3758,9 +4541,11 @@ function apply(ctx) {
3758
4541
  ctx.logger.warn(`roleplay: ${message}`);
3759
4542
  };
3760
4543
  const sessionsDir = () => join(ctx.roleplayRoot.path, "sessions");
3761
- const decisions = () => ctx.get("decisions");
4544
+ const residency = () => ctx.roleplayOrchestration.residency;
4545
+ const decisions = () => guarded(residency(), "decision", ctx.get("decisions"), ["decide"]);
4546
+ const embeddings = () => guarded(residency(), "embedding", ctx.get("embeddings"), ["embed"]);
3762
4547
  const index = new EmbeddingIndex({
3763
- embedder: () => ctx.get("embeddings"),
4548
+ embedder: embeddings,
3764
4549
  story: (chat) => {
3765
4550
  const id = roleplaySessionOf(chat);
3766
4551
  if (id === void 0) return void 0;
@@ -3778,7 +4563,7 @@ function apply(ctx) {
3778
4563
  });
3779
4564
  ctx.inject(["rerankers"], (scope) => {
3780
4565
  scope.effect(() => ctx.roleplayState.rankMemories(rerankMemories({
3781
- reranker: () => scope.rerankers,
4566
+ reranker: () => guarded(residency(), "reranker", scope.rerankers, ["rerank"]),
3782
4567
  problem
3783
4568
  })), "roleplay: rerank memories");
3784
4569
  });
@@ -3791,6 +4576,7 @@ function apply(ctx) {
3791
4576
  ctx.effect(() => ctx.roleplayOrchestration.replace({ outputGate: outputGates({
3792
4577
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
3793
4578
  decisions,
4579
+ earlier: (chat, count) => timelines.narrationBefore(chat, count),
3794
4580
  problem
3795
4581
  }) }), "roleplay: output gates");
3796
4582
  ctx.effect(() => ctx.roleplayOrchestration.replace({ ruleCheck: ruleChecks({
@@ -3807,6 +4593,15 @@ function apply(ctx) {
3807
4593
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
3808
4594
  external: (parent) => ctx.get("roleplayAuthoringTools")?.given(parent.ctx.tools, "worldAuthor") ?? []
3809
4595
  }) }), "roleplay: world author");
4596
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ errandKeeper: errandChecks({
4597
+ decisions,
4598
+ problem
4599
+ }) }), "roleplay: errands");
4600
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ variableTracker: variableTracker({
4601
+ agentOf: (chat) => ctx.agents.get(SessionId(chat)),
4602
+ decisions,
4603
+ problem
4604
+ }) }), "roleplay: tracked values");
3810
4605
  ctx.effect(() => ctx.roleplayOrchestration.replace({ suggester: suggestionWriter({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: suggestions");
3811
4606
  ctx.effect(() => ctx.roleplayState.bind((agentSessionId) => {
3812
4607
  const id = roleplaySessionOf(agentSessionId);
@@ -3840,7 +4635,7 @@ function apply(ctx) {
3840
4635
  "list_checks"
3841
4636
  ].filter((tool) => toolEnabled(chat.settings.tools, "gameMaster", tool));
3842
4637
  if (on.length === 0) return "";
3843
- const checks = on.includes("roll_check") ? describeChecks(store.story.dice.checks(), translator(languageOf(language))) : "";
4638
+ const checks = on.includes("roll_check") ? describeChecks(store.story.dice.checks(), translator(languageOf$1(language))) : "";
3844
4639
  return ctx.roleplayPrompts.text("roleplay/dice", language, {
3845
4640
  tools: on.join(", "),
3846
4641
  checks
@@ -3849,7 +4644,7 @@ function apply(ctx) {
3849
4644
  /** What the world carries as standing rules (the card's always-on rules), with a line that says what they are; nothing for a world that has none. */
3850
4645
  const standingSection = (text, language) => {
3851
4646
  if (text.trim() === shippedText("roleplay/standing", language).trim()) return "";
3852
- return `${translator(languageOf(language))("The standing rules of this world. Apply them on every turn:")}\n\n${text}`;
4647
+ return `${translator(languageOf$1(language))("The standing rules of this world. Apply them on every turn:")}\n\n${text}`;
3853
4648
  };
3854
4649
  for (const [name, order, id] of [[
3855
4650
  PERSONA_SECTION,
@@ -3881,7 +4676,7 @@ function apply(ctx) {
3881
4676
  interpolate: false,
3882
4677
  text: (context) => {
3883
4678
  const chat = settingsOf(context);
3884
- return resourceHint(ctx.tools.schemas(context.scope).map((tool) => tool.name), ctx.tools.schemas().map((tool) => tool.name), translator(languageOf(chat?.settings.prompts.language ?? "en")));
4679
+ return resourceHint(ctx.tools.schemas(context.scope).map((tool) => tool.name), ctx.tools.schemas().map((tool) => tool.name), translator(languageOf$1(chat?.settings.prompts.language ?? "en")));
3885
4680
  }
3886
4681
  });
3887
4682
  ctx.systemPrompt.context({
@@ -3891,6 +4686,7 @@ function apply(ctx) {
3891
4686
  text: ""
3892
4687
  });
3893
4688
  const rolls = new RollReplay((chat) => stores(chat)?.settings().rewind.rolls ?? "reroll");
4689
+ const turnTraces = new TurnTraces(() => tracerOf(ctx));
3894
4690
  const toolDeps = {
3895
4691
  engine,
3896
4692
  boundaries,
@@ -3898,6 +4694,7 @@ function apply(ctx) {
3898
4694
  turnOf: currentTurn,
3899
4695
  roller: (chat) => rolls.roller(chat),
3900
4696
  delivered: (chat, output) => {
4697
+ turnTraces.output(chat, output.segments.map((segment) => segment.type === "utterance" ? `${segment.name}: ${segment.text}` : segment.text).join("\n\n"));
3901
4698
  const node = timelines.delivered(chat, output);
3902
4699
  if (node !== void 0) images.afterDelivery(chat, node, output);
3903
4700
  return node;
@@ -3917,6 +4714,43 @@ function apply(ctx) {
3917
4714
  ctx.roleplayOrchestration.playing = () => false;
3918
4715
  };
3919
4716
  }, "roleplay: reflection control");
4717
+ ctx.effect(() => {
4718
+ ctx.roleplayOrchestration.autonomy = async (chat, signal) => {
4719
+ const started = Date.now();
4720
+ const run = await tickAutonomy({
4721
+ engine,
4722
+ stores,
4723
+ boundaries,
4724
+ agentOf: (id) => ctx.agents.get(SessionId(id)),
4725
+ wall: Date.now,
4726
+ problem,
4727
+ decisions
4728
+ }, chat, signal);
4729
+ stores(chat)?.autonomy?.looked?.(run.outcome, Date.now());
4730
+ const tracer = tracerOf(ctx);
4731
+ if (tracer !== void 0 && (run.moved > 0 || run.outcome === "wrote" || run.outcome === "declined")) tracer.start({
4732
+ name: "autonomy look",
4733
+ kind: "span",
4734
+ metadata: {
4735
+ outcome: run.outcome,
4736
+ moved: run.moved,
4737
+ seconds: (Date.now() - started) / 1e3
4738
+ },
4739
+ trace: {
4740
+ name: "autonomy look",
4741
+ sessionId: sessionOfChat(chat),
4742
+ tags: ["roleplay", "autonomy"]
4743
+ }
4744
+ }).end({ output: run });
4745
+ return run;
4746
+ };
4747
+ return () => {
4748
+ ctx.roleplayOrchestration.autonomy = () => Promise.resolve({
4749
+ outcome: "off",
4750
+ moved: 0
4751
+ });
4752
+ };
4753
+ }, "roleplay: autonomy");
3920
4754
  ctx.effect(() => {
3921
4755
  ctx.roleplayOrchestration.settle = (chat) => engine.idle(chat);
3922
4756
  return () => {
@@ -3936,11 +4770,24 @@ function apply(ctx) {
3936
4770
  state: ctx.roleplayState,
3937
4771
  sessionsDir,
3938
4772
  timelines,
3939
- service: () => ctx.get("imageGeneration"),
4773
+ service: () => guarded(residency(), "image", ctx.get("imageGeneration"), ["generate"]),
4774
+ turnStore: (chat) => stores(chat),
4775
+ reuseExisting: pictureReuse({
4776
+ decisions,
4777
+ embedder: embeddings,
4778
+ problem
4779
+ }),
4780
+ beforeGeneration: async (chat, signal) => {
4781
+ if (residency()?.conflicts("image", "main") === true) await Promise.race([engine.quiesce(chat), new Promise((resolve) => {
4782
+ signal.addEventListener("abort", () => {
4783
+ resolve();
4784
+ }, { once: true });
4785
+ })]);
4786
+ },
3940
4787
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
3941
4788
  settings: (id) => liveSettings(sessionFolder(sessionsDir(), id), problem),
3942
4789
  attachments: () => ctx.get("attachments"),
3943
- embedder: () => ctx.get("embeddings"),
4790
+ embedder: embeddings,
3944
4791
  problem
3945
4792
  });
3946
4793
  imageJobs = images;
@@ -3977,12 +4824,21 @@ function apply(ctx) {
3977
4824
  turn: currentTurn(agent)
3978
4825
  };
3979
4826
  };
4827
+ registerFoldersJail(ctx, {
4828
+ roots: async (session) => await storyRoots(ctx.roleplayRoot.path, sessionFolder(sessionsDir(), session)),
4829
+ workspace: () => workspaceOf(ctx.roleplayRoot.path)
4830
+ });
3980
4831
  installHooks(ctx, {
4832
+ traces: turnTraces,
3981
4833
  engine,
3982
4834
  boundaries,
3983
4835
  stores,
3984
4836
  timelines,
3985
4837
  rolls,
4838
+ folders: async (chat) => {
4839
+ const session = roleplaySessionOf(chat);
4840
+ return session === void 0 ? void 0 : await storyRoots(ctx.roleplayRoot.path, sessionFolder(sessionsDir(), session));
4841
+ },
3986
4842
  previewTool,
3987
4843
  optionalTools: [...createDiceTools(diceLink, { rollerFor: (chat) => rolls.roller(chat) }), createCheckNarrateTool(toolDeps)]
3988
4844
  });