@dsh-agentic-roleplay/core 0.11.1 → 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 (50) hide show
  1. package/lib/{access-Md1YTSX1.js → access-DAw54-NI.js} +3 -15
  2. package/lib/{authoring-tools-BFdw7ahj.js → authoring-tools-4NgDhIJV.js} +51 -11
  3. package/lib/authoring.js +8 -8
  4. package/lib/{child-C9nPIy9j.js → child-D3QUNb3m.js} +121 -2
  5. package/lib/client.js +1013 -449
  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-BWHmjogd.js → gallery-Ct6nm4UQ.js} +3 -3
  10. package/lib/{generator-QCdm8nUh.js → generator-CI8fOnXy.js} +2 -2
  11. package/lib/helper.js +13 -1
  12. package/lib/{hooks-C2U1-8ur.js → hooks-BNeoGMHZ.js} +722 -334
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +234 -20
  15. package/lib/jail-BIF79PJO.js +107 -0
  16. package/lib/{library-4zmCAshR.js → library-BF9ZMSFz.js} +3 -3
  17. package/lib/{lorebook-author-tools-Bjfjt3bg.js → lorebook-author-tools-DBk-V0hp.js} +7 -7
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-b_VBEUWn.js → narration-xvErE2yp.js} +29 -2
  20. package/lib/orchestration.js +593 -47
  21. package/lib/{pack-jail-Ci9bIeDI.js → pack-jail-C8EyX9Ix.js} +12 -11
  22. package/lib/{packs-CYkozh8Q.js → packs-S0SzrVv-.js} +2 -2
  23. package/lib/{presenter-agent-CqkAL03Q.js → presenter-agent-Bc478nTA.js} +6 -6
  24. package/lib/{preset-B-35yUmt.js → preset-SJZyw0kt.js} +4 -4
  25. package/lib/{preset-author-tools-BUymqZM5.js → preset-author-tools-CzogjK42.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-_U-xroo0.js → presets-DQ5rioMh.js} +231 -48
  28. package/lib/{reflection-B9N0z3KY.js → reflection-buQiSdvq.js} +15 -8
  29. package/lib/service-mRKwpWjX.js +140 -0
  30. package/lib/{text-C2AGl7Je.js → text-Dfv8S8eq.js} +27 -2
  31. package/lib/{turn-guard-C0M3rXEN.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 +2 -1
  37. package/prompts/en/roleplay/character-lookup.md +1 -1
  38. package/prompts/en/roleplay/decide-errand.md +1 -0
  39. package/prompts/en/roleplay/decide-message.md +1 -0
  40. package/prompts/en/roleplay/dream.md +1 -0
  41. package/prompts/en/roleplay/gate-repeat.md +1 -0
  42. package/prompts/zh/import/finish-ok.md +1 -1
  43. package/prompts/zh/import/generator.md +1 -1
  44. package/prompts/zh/import/style.md +1 -1
  45. package/prompts/zh/import/variables.md +2 -1
  46. package/prompts/zh/roleplay/character-lookup.md +1 -1
  47. package/prompts/zh/roleplay/decide-errand.md +1 -0
  48. package/prompts/zh/roleplay/decide-message.md +1 -0
  49. package/prompts/zh/roleplay/dream.md +1 -0
  50. package/prompts/zh/roleplay/gate-repeat.md +1 -0
@@ -1,16 +1,18 @@
1
- import { c as chatSessionId, l as roleplaySessionOf, t as promptFor } from "./access-Md1YTSX1.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, at as shippedText, c as record, f as MAX_OOC_ANSWER, gt as AUTHORING_NEEDS, ht as zoneOf, l as characterRunner, lt as ReflectionRefusedError, mt as describeWhen, n as installHooks, o as PREVIEW_TOOL, p as storesOf, pt as ClockError, r as externalGiven, s as createTools$1, u as toolEnabled, v as readVerdicts, y as writeVerdicts } from "./hooks-C2U1-8ur.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, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-B9N0z3KY.js";
5
- import { B as modeFor, H as routeVerdicts, Ht as INTENT_STATUSES, L as announceProblem, Lt as guarded, R as askYesNo, U as yesAt, V as noAt, m as STANDING_PROMPT } from "./presets-_U-xroo0.js";
6
- import { i as translator, r as languageOf } from "./text-C2AGl7Je.js";
7
- import { a as liveSettings, g as GATE_SITES, n as encodeOutput } from "./narration-b_VBEUWn.js";
8
- import { C as slug, T as uniqueKey, t as addToLibrary } from "./library-4zmCAshR.js";
9
- import { _ as API_PREFIX } from "./packs-CYkozh8Q.js";
10
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-BWHmjogd.js";
11
- import { c as presentedFor, i as findImages, n as interpretImage, s as present, t as runImagePresenter } from "./presenter-agent-CqkAL03Q.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",
@@ -412,7 +414,7 @@ function suggestionWriter(deps) {
412
414
  trace: childTrace(job.store, "suggestions", "suggestions"),
413
415
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
414
416
  prompt: promptOf(job),
415
- result: RESULT$3,
417
+ result: RESULT$4,
416
418
  structured: true,
417
419
  beforeSubmit: (value) => {
418
420
  const problems = suggestionProblems(wanted(value.options, job.count), job.count);
@@ -424,7 +426,7 @@ function suggestionWriter(deps) {
424
426
  } };
425
427
  }
426
428
  // src/host/triggers/judge.ts
427
- const RESULT$2 = {
429
+ const RESULT$3 = {
428
430
  type: "object",
429
431
  properties: { verdicts: {
430
432
  type: "array",
@@ -454,7 +456,7 @@ const RESULT$2 = {
454
456
  additionalProperties: false
455
457
  };
456
458
  /** The longest reason a verdict gives, in characters: what the answer is given room for besides its number and its yes or no. */
457
- const REASON_CHARS$1 = 600;
459
+ const REASON_CHARS$2 = 600;
458
460
  /** The statements of the triggers still waiting, each once. */
459
461
  function waitingStatements(job) {
460
462
  return [...new Set(job.store.story.triggers.list({ status: "dormant" }).flatMap((trigger) => judgedStatements(trigger.condition)))];
@@ -503,7 +505,7 @@ function triggerJudge(deps) {
503
505
  turn: job.turn,
504
506
  reasoningEffort: settings.reasoning.children,
505
507
  sampling: childSampling(settings, "records", estimateAnswer(subset.flatMap(() => [
506
- REASON_CHARS$1,
508
+ REASON_CHARS$2,
507
509
  0,
508
510
  0
509
511
  ]), settings.prompts.language)),
@@ -511,7 +513,7 @@ function triggerJudge(deps) {
511
513
  trace: childTrace(store, "records", "trigger judge"),
512
514
  persona: promptFor(parent, "roleplay/trigger-judge", settings.prompts.language),
513
515
  prompt: brief$2(scene, subset),
514
- result: RESULT$2,
516
+ result: RESULT$3,
515
517
  beforeSubmit: (value) => {
516
518
  const numbers = value.verdicts.map((verdict) => verdict.number);
517
519
  const missing = subset.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
@@ -633,6 +635,105 @@ function ruleChecks(deps) {
633
635
  return found.map((key) => rules[Number(key.slice(4))]);
634
636
  } };
635
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
+ }
636
737
  // src/host/decisions/gates.ts
637
738
  /**
638
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
@@ -688,7 +789,7 @@ function outputGates(deps) {
688
789
  return { async check(job, signal) {
689
790
  const settings = job.store.settings();
690
791
  const parent = deps.agentOf(job.chat);
691
- return [...(await Promise.all(GATE_SITES.map(async (site) => {
792
+ const found = await Promise.all(GATE_SITES.map(async (site) => {
692
793
  const mode = settings.decisions[site];
693
794
  const gate = GATES[site];
694
795
  if (mode === "off" || !gate.applies(job)) return [];
@@ -737,7 +838,19 @@ function outputGates(deps) {
737
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)}`);
738
839
  return [];
739
840
  }
740
- }))).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
+ ];
741
854
  } };
742
855
  }
743
856
  const SECRET_PROMPT = "roleplay/gate-secret";
@@ -761,7 +874,7 @@ async function secretFindings(job, decisions, service, seen, signal, say) {
761
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. */
762
875
  const BAND = .15;
763
876
  /** What the models are shown of the turn, in characters: enough for what happened, never the whole story. */
764
- const NARRATION_CHARS = 2400;
877
+ const NARRATION_CHARS$1 = 2400;
765
878
  const DEEDS_CHARS = 2400;
766
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. */
767
880
  const verdictSchema = (keys) => ({
@@ -829,9 +942,9 @@ function question(store, item, tr) {
829
942
  function brief$1(job, items, tr, heading) {
830
943
  const range = (def) => def.kind === "number" ? ` (${def.min ?? "…"} to ${def.max ?? "…"}${def.integer ? ", whole numbers" : ""})` : def.kind === "choice" ? ` (${def.options.join(", ")})` : "";
831
944
  return [
832
- job.input.trim() === "" ? void 0 : `${tr("What the player wrote:")}\n${job.input.slice(0, NARRATION_CHARS)}`,
945
+ job.input.trim() === "" ? void 0 : `${tr("What the player wrote:")}\n${job.input.slice(0, NARRATION_CHARS$1)}`,
833
946
  `${tr("What the characters did and said:")}\n${job.deeds.join("\n").slice(0, DEEDS_CHARS)}`,
834
- `${tr("What the player read:")}\n${job.narration.slice(0, NARRATION_CHARS)}`,
947
+ `${tr("What the player read:")}\n${job.narration.slice(0, NARRATION_CHARS$1)}`,
835
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")}`
836
949
  ].filter((part) => part !== void 0).join("\n\n");
837
950
  }
@@ -849,7 +962,7 @@ function variableTracker(deps) {
849
962
  const items = trackedItems(job.store, `${job.input}\n${job.deeds.join("\n")}\n${job.narration}`);
850
963
  if (items.length === 0) return 0;
851
964
  const parent = deps.agentOf(job.chat);
852
- const tr = translator(languageOf(settings.prompts.language));
965
+ const tr = translator(languageOf$1(settings.prompts.language));
853
966
  const byKey = new Map(items.map((item) => [item.key, item]));
854
967
  const personaOf = (id) => parent === void 0 ? job.store.text(id) : promptFor(parent, id, settings.prompts.language);
855
968
  const ask = async (persona, prompt, result, answers, label) => {
@@ -888,7 +1001,7 @@ function variableTracker(deps) {
888
1001
  if (service === void 0) throw new Error("no decision service is selected, or the selected one is not loaded");
889
1002
  const state = {
890
1003
  happened: job.deeds.join("\n").slice(0, DEEDS_CHARS),
891
- narration: job.narration.slice(0, NARRATION_CHARS),
1004
+ narration: job.narration.slice(0, NARRATION_CHARS$1),
892
1005
  ...job.input.trim() === "" ? {} : { player_wrote: job.input }
893
1006
  };
894
1007
  return await askYesNo(service, state, keys.map((key) => ({
@@ -945,6 +1058,57 @@ function variableTracker(deps) {
945
1058
  }
946
1059
  } };
947
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
+ }
948
1112
  // src/host/factions/strategist.ts
949
1113
  const LAST_KEY = "strategy.last";
950
1114
  const DAY_MS = 864e5;
@@ -1588,6 +1752,168 @@ var RollReplay = class {
1588
1752
  };
1589
1753
  }
1590
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
+ }
1591
1917
  // src/host/orchestration/check-tool.ts
1592
1918
  const CHECK_NARRATE_TOOL = "roll_and_narrate";
1593
1919
  const BRANCHES = [
@@ -1881,7 +2207,7 @@ function rerankMemories(deps) {
1881
2207
  * someone to talk to, a way out, a thing to look at, then plain standbys. No model is asked.
1882
2208
  */
1883
2209
  function fallbackSuggestions(store, count) {
1884
- const tr = translator(languageOf(store.settings().prompts.language));
2210
+ const tr = translator(languageOf$1(store.settings().prompts.language));
1885
2211
  const player = store.cast().find((member) => member.character.control === "player");
1886
2212
  const view = player?.place === void 0 ? void 0 : store.place(player.place.location.id);
1887
2213
  const people = (view?.here ?? []).filter((member) => member.character.id !== player?.character.id).map((member) => tr("Talk to {name}.", { name: member.character.name }));
@@ -1921,11 +2247,13 @@ var AfterTurnJobs = class {
1921
2247
  reflecting = /* @__PURE__ */ new Set();
1922
2248
  casting = /* @__PURE__ */ new Set();
1923
2249
  tracking = /* @__PURE__ */ new Set();
2250
+ erranding = /* @__PURE__ */ new Set();
1924
2251
  constructor(deps) {
1925
2252
  this.deps = deps;
1926
2253
  }
1927
2254
  start(owner, cancel, facts) {
1928
2255
  if (facts !== void 0) this.trackVariables(owner, cancel, facts);
2256
+ if (facts !== void 0) this.keepErrands(owner, cancel, facts);
1929
2257
  this.consolidate(owner, cancel);
1930
2258
  this.strategize(owner, cancel);
1931
2259
  this.judge(owner, cancel);
@@ -1951,6 +2279,24 @@ var AfterTurnJobs = class {
1951
2279
  this.tracking.delete(owner.chat);
1952
2280
  }));
1953
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
+ }
1954
2300
  /** Whether a reflection is running for the chat. */
1955
2301
  isReflecting(chat) {
1956
2302
  return this.reflecting.has(chat);
@@ -2179,7 +2525,7 @@ function explainPhase(state, attempted) {
2179
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";
2180
2526
  const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
2181
2527
  switch (state.phase) {
2182
- 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";
2183
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)}`;
2184
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)}`;
2185
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)}`;
@@ -2382,6 +2728,7 @@ async function askCharacters(deps, owner, number, keys, cast, state, run, signal
2382
2728
  text: (id, variables) => deps.storeOf(owner).text(id, variables),
2383
2729
  ...time === void 0 ? {} : { time },
2384
2730
  ...agenda === void 0 ? {} : { agenda },
2731
+ ...state.dreaming === key ? { dreaming: true } : {},
2385
2732
  ...cues.length === 0 ? {} : { cues },
2386
2733
  ...upcoming.length === 0 ? {} : { upcoming },
2387
2734
  ...tracked === void 0 || tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
@@ -2435,6 +2782,13 @@ async function askCharacters(deps, owner, number, keys, cast, state, run, signal
2435
2782
  };
2436
2783
  }
2437
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
+ }
2438
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. */
2439
2793
  function recordRound(store, owner, state, fire) {
2440
2794
  const decided = decisions(state);
@@ -2481,6 +2835,10 @@ function recordRound(store, owner, state, fire) {
2481
2835
  ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() }
2482
2836
  },
2483
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
+ } } : {},
2484
2842
  ...outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 ? {} : { items: outcome.itemChanges }
2485
2843
  }
2486
2844
  }];
@@ -2758,7 +3116,30 @@ function asSpoken(segments, spoken) {
2758
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.
2759
3117
  * A refusal is thrown for the game master to correct; past `MAX_REFUSALS`, or when `silent`, the output is repaired instead.
2760
3118
  */
2761
- 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;
2762
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)];
2763
3144
  const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") }, { strays: true });
2764
3145
  if (problems.length === 0 && wording !== void 0 && !silent && state.refused < 2) {
@@ -2767,7 +3148,7 @@ function checkedOutput(narrationChecker, language, state, segments, silent) {
2767
3148
  }
2768
3149
  if (problems.length === 0) return {
2769
3150
  segments: asSpoken(segments, state.utterances),
2770
- repaired: false
3151
+ repaired: cleaned.found
2771
3152
  };
2772
3153
  state.refused += 1;
2773
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`);
@@ -2833,7 +3214,10 @@ async function runOffScene(deps, owner, state, store, due, limit) {
2833
3214
  return member === void 0 ? [] : [{
2834
3215
  character: member.character.id,
2835
3216
  patch: { activity: report.intent },
2836
- ...move?.ok === true ? { move: move.move } : {}
3217
+ ...move?.ok === true ? {
3218
+ move: move.move,
3219
+ hold: {}
3220
+ } : {}
2837
3221
  }];
2838
3222
  }));
2839
3223
  state.offstage += 1;
@@ -2876,7 +3260,11 @@ async function runOffScene(deps, owner, state, store, due, limit) {
2876
3260
  }
2877
3261
  }
2878
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";
2879
3266
  const MAX_OBJECTIONS = 3;
3267
+ const MAX_PREVIEW_REFUSALS = 3;
2880
3268
  /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
2881
3269
  const MAX_ROUND_SECONDS = 86400;
2882
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. */
@@ -2909,6 +3297,8 @@ var TurnEngine = class {
2909
3297
  reflectionCancels = /* @__PURE__ */ new Map();
2910
3298
  /** Chats whose characters away from the player are being asked about what fell due: one run at a time. */
2911
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;
2912
3302
  constructor(boundaries, stores, problem = () => void 0, written = () => void 0) {
2913
3303
  this.boundaries = boundaries;
2914
3304
  this.stores = stores;
@@ -2932,6 +3322,30 @@ var TurnEngine = class {
2932
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
2933
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.
2934
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
+ }
2935
3349
  beginOoc(owner, request, question = false) {
2936
3350
  const state = this.stateFor(owner);
2937
3351
  state.ooc = {
@@ -2987,7 +3401,7 @@ var TurnEngine = class {
2987
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.
2988
3402
  * @throws {Error} when the turn is not an ordinary one, was already judged, the reason is empty, or `at` is not a place.
2989
3403
  */
2990
- judge(owner, allowed, reason, at, uncertain) {
3404
+ judge(owner, allowed, reason, at, uncertain, goesTo) {
2991
3405
  const state = this.stateFor(owner);
2992
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"));
2993
3407
  if (state.phase !== "idle") throw new Error("the action is judged first, before anything else");
@@ -3012,9 +3426,16 @@ var TurnEngine = class {
3012
3426
  };
3013
3427
  }
3014
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
+ }
3015
3435
  state.judgement = {
3016
3436
  allowed,
3017
- reason: why
3437
+ reason: why,
3438
+ ...allowed && destination !== "" ? { goesTo: destination } : {}
3018
3439
  };
3019
3440
  const { tools } = this.storeOf(owner).settings();
3020
3441
  if (allowed && uncertain === true && (toolEnabled(tools, "gameMaster", "roll_check") || toolEnabled(tools, "gameMaster", "roll_dice"))) {
@@ -3065,11 +3486,12 @@ var TurnEngine = class {
3065
3486
  */
3066
3487
  async activate(owner, input, run, signal) {
3067
3488
  const state = this.stateFor(owner);
3489
+ if (state.dreamed === true) throw new Error(DREAM_ASKED);
3068
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");
3069
3491
  if (state.phase !== "idle" && state.phase !== "between") throw new Error(explainPhase(state, "activate_characters"));
3070
3492
  if (judgeDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3071
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`);
3072
- if (previewDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3494
+ if (this.previewHeld(state)) throw new Error(explainPhase(state, "activate_characters"));
3073
3495
  if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
3074
3496
  const store = this.storeOf(owner);
3075
3497
  const limit = store.settings().maxRounds;
@@ -3078,11 +3500,25 @@ var TurnEngine = class {
3078
3500
  if (situation === "") throw new Error("describe the situation: the characters are told nothing else");
3079
3501
  const cast = store.cast();
3080
3502
  const most = store.settings().maxCharacters;
3081
- const keys = this.boundaries().planner.plan({
3503
+ const planned = this.boundaries().planner.plan({
3082
3504
  cast,
3083
3505
  ...input.characters === void 0 ? {} : { requested: input.characters }
3084
3506
  });
3085
- 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)]);
3086
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`);
3087
3523
  const signature = `${[...keys].sort((a, b) => a.localeCompare(b)).join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
3088
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");
@@ -3115,10 +3551,11 @@ var TurnEngine = class {
3115
3551
  async resolve(owner, outcomes, run, signal, elapsedSeconds) {
3116
3552
  const state = this.stateFor(owner);
3117
3553
  const store = this.storeOf(owner);
3554
+ if (state.dreamed === true) throw new Error(DREAM_ASKED);
3118
3555
  outcomes = mendRolls(outcomes, store, state);
3119
3556
  if (state.ooc !== void 0) return { done: this.decree(owner, state, outcomes, elapsedSeconds) };
3120
3557
  if (state.phase === "idle" || state.phase === "between") {
3121
- 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"));
3122
3559
  if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
3123
3560
  const player = store.cast().find((member) => member.character.control === "player");
3124
3561
  if (player !== void 0 && outcomes.length === 1 && outcomes[0]?.character === player.key) return { done: this.resolvePlayer(owner, state, outcomes[0], elapsedSeconds) };
@@ -3187,6 +3624,14 @@ var TurnEngine = class {
3187
3624
  };
3188
3625
  return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
3189
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
+ }
3190
3635
  /** The turn settles a lone attempt in one step: nobody is asked to act, so there is no scene to preview. */
3191
3636
  withoutPreview(owner) {
3192
3637
  this.stateFor(owner).previewWanted = false;
@@ -3297,11 +3742,13 @@ var TurnEngine = class {
3297
3742
  */
3298
3743
  async narrate(owner, segments, run, addressed = []) {
3299
3744
  const state = this.stateFor(owner);
3745
+ if (state.phase === "idle") this.previewHeld(state);
3300
3746
  if (state.phase !== "between") throw new Error(explainPhase(state, "narrate"));
3301
3747
  const pending = new Set(this.storeOf(owner).pendingBeats().map((beat) => beat.id));
3302
3748
  const unknown = addressed.filter((id) => !pending.has(id));
3303
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)`);
3304
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");
3305
3752
  if (state.ooc !== void 0) {
3306
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");
3307
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");
@@ -3337,7 +3784,9 @@ var TurnEngine = class {
3337
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.
3338
3785
  */
3339
3786
  async expand(owner, input, signal) {
3340
- 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);
3341
3790
  }
3342
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. */
3343
3792
  introduce(owner, input) {
@@ -3557,7 +4006,12 @@ var TurnEngine = class {
3557
4006
  stateFor({ chat, turn }) {
3558
4007
  const known = this.states.get(chat);
3559
4008
  if (known?.turn === turn) return known;
3560
- 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 {
3561
4015
  turn,
3562
4016
  phase: "idle",
3563
4017
  cast: [],
@@ -3573,6 +4027,7 @@ var TurnEngine = class {
3573
4027
  reported: /* @__PURE__ */ new Set(),
3574
4028
  refused: 0,
3575
4029
  previewed: false,
4030
+ previewRefusals: 0,
3576
4031
  previewWanted: this.stores(chat)?.settings().preview.enabled ?? false,
3577
4032
  focus: [],
3578
4033
  requested: false,
@@ -3582,8 +4037,16 @@ var TurnEngine = class {
3582
4037
  cues: /* @__PURE__ */ new Map(),
3583
4038
  addressed: []
3584
4039
  };
3585
- this.states.set(chat, fresh);
3586
- 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];
3587
4050
  }
3588
4051
  storeOf(owner) {
3589
4052
  const store = this.stores(owner.chat);
@@ -3591,7 +4054,13 @@ var TurnEngine = class {
3591
4054
  return store;
3592
4055
  }
3593
4056
  ask(owner, number, keys, cast, state, run, signal, away = false) {
3594
- 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({
3595
4064
  boundaries: this.boundaries(),
3596
4065
  store: this.stores(owner.chat),
3597
4066
  storeOf: (o) => this.storeOf(o),
@@ -3599,6 +4068,14 @@ var TurnEngine = class {
3599
4068
  this.problem(message);
3600
4069
  }
3601
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
+ });
3602
4079
  }
3603
4080
  /**
3604
4081
  * The game master asks for what happened to be written into the story's lasting records. The memory
@@ -3726,8 +4203,24 @@ var TurnEngine = class {
3726
4203
  state.refused += 1;
3727
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`);
3728
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
+ }
3729
4221
  async deliver(owner, state, segments, silent, run) {
3730
4222
  let output = checkedOutput(this.boundaries().narrationChecker, this.storeOf(owner).settings().prompts.language, state, segments, silent);
4223
+ this.checkArrival(owner, state, silent);
3731
4224
  await this.gate(owner, state, output, silent);
3732
4225
  if (state.ooc?.ruling !== void 0) output = {
3733
4226
  ...output,
@@ -4019,7 +4512,7 @@ function pictureReuse(deps) {
4019
4512
  key: `picture${index}`,
4020
4513
  instructions: job.store.text("roleplay/decide-reuse", { description: image.description.trim() })
4021
4514
  }));
4022
- const { found, report } = await askExtra(deps.decisions?.(), { moment: job.moment.slice(0, MOMENT_CHARS) }, asks, settings.decisions.gateThreshold, signal);
4515
+ const { found, report } = await askExtra(deps.decisions?.(), { moment: job.moment.slice(0, MOMENT_CHARS) }, asks, settings.decisions.reuseThreshold, signal);
4023
4516
  noteExtra("reuse", job.chat, job.store, report, seen, deps.problem);
4024
4517
  const first = found[0];
4025
4518
  return first === void 0 ? void 0 : matches[Number(first.slice(7))].image.path;
@@ -4083,6 +4576,7 @@ function apply(ctx) {
4083
4576
  ctx.effect(() => ctx.roleplayOrchestration.replace({ outputGate: outputGates({
4084
4577
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
4085
4578
  decisions,
4579
+ earlier: (chat, count) => timelines.narrationBefore(chat, count),
4086
4580
  problem
4087
4581
  }) }), "roleplay: output gates");
4088
4582
  ctx.effect(() => ctx.roleplayOrchestration.replace({ ruleCheck: ruleChecks({
@@ -4099,6 +4593,10 @@ function apply(ctx) {
4099
4593
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
4100
4594
  external: (parent) => ctx.get("roleplayAuthoringTools")?.given(parent.ctx.tools, "worldAuthor") ?? []
4101
4595
  }) }), "roleplay: world author");
4596
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ errandKeeper: errandChecks({
4597
+ decisions,
4598
+ problem
4599
+ }) }), "roleplay: errands");
4102
4600
  ctx.effect(() => ctx.roleplayOrchestration.replace({ variableTracker: variableTracker({
4103
4601
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
4104
4602
  decisions,
@@ -4137,7 +4635,7 @@ function apply(ctx) {
4137
4635
  "list_checks"
4138
4636
  ].filter((tool) => toolEnabled(chat.settings.tools, "gameMaster", tool));
4139
4637
  if (on.length === 0) return "";
4140
- 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))) : "";
4141
4639
  return ctx.roleplayPrompts.text("roleplay/dice", language, {
4142
4640
  tools: on.join(", "),
4143
4641
  checks
@@ -4146,7 +4644,7 @@ function apply(ctx) {
4146
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. */
4147
4645
  const standingSection = (text, language) => {
4148
4646
  if (text.trim() === shippedText("roleplay/standing", language).trim()) return "";
4149
- 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}`;
4150
4648
  };
4151
4649
  for (const [name, order, id] of [[
4152
4650
  PERSONA_SECTION,
@@ -4178,7 +4676,7 @@ function apply(ctx) {
4178
4676
  interpolate: false,
4179
4677
  text: (context) => {
4180
4678
  const chat = settingsOf(context);
4181
- 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")));
4182
4680
  }
4183
4681
  });
4184
4682
  ctx.systemPrompt.context({
@@ -4188,6 +4686,7 @@ function apply(ctx) {
4188
4686
  text: ""
4189
4687
  });
4190
4688
  const rolls = new RollReplay((chat) => stores(chat)?.settings().rewind.rolls ?? "reroll");
4689
+ const turnTraces = new TurnTraces(() => tracerOf(ctx));
4191
4690
  const toolDeps = {
4192
4691
  engine,
4193
4692
  boundaries,
@@ -4195,6 +4694,7 @@ function apply(ctx) {
4195
4694
  turnOf: currentTurn,
4196
4695
  roller: (chat) => rolls.roller(chat),
4197
4696
  delivered: (chat, output) => {
4697
+ turnTraces.output(chat, output.segments.map((segment) => segment.type === "utterance" ? `${segment.name}: ${segment.text}` : segment.text).join("\n\n"));
4198
4698
  const node = timelines.delivered(chat, output);
4199
4699
  if (node !== void 0) images.afterDelivery(chat, node, output);
4200
4700
  return node;
@@ -4214,6 +4714,43 @@ function apply(ctx) {
4214
4714
  ctx.roleplayOrchestration.playing = () => false;
4215
4715
  };
4216
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");
4217
4754
  ctx.effect(() => {
4218
4755
  ctx.roleplayOrchestration.settle = (chat) => engine.idle(chat);
4219
4756
  return () => {
@@ -4287,12 +4824,21 @@ function apply(ctx) {
4287
4824
  turn: currentTurn(agent)
4288
4825
  };
4289
4826
  };
4827
+ registerFoldersJail(ctx, {
4828
+ roots: async (session) => await storyRoots(ctx.roleplayRoot.path, sessionFolder(sessionsDir(), session)),
4829
+ workspace: () => workspaceOf(ctx.roleplayRoot.path)
4830
+ });
4290
4831
  installHooks(ctx, {
4832
+ traces: turnTraces,
4291
4833
  engine,
4292
4834
  boundaries,
4293
4835
  stores,
4294
4836
  timelines,
4295
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
+ },
4296
4842
  previewTool,
4297
4843
  optionalTools: [...createDiceTools(diceLink, { rollerFor: (chat) => rolls.roller(chat) }), createCheckNarrateTool(toolDeps)]
4298
4844
  });