@dsh-agentic-roleplay/core 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/lib/{access-Md1YTSX1.js → access-DifaiHrI.js} +3 -15
  2. package/lib/{authoring-tools-BFdw7ahj.js → authoring-tools-VOaXzr_R.js} +58 -766
  3. package/lib/authoring.js +136 -13
  4. package/lib/{child-C9nPIy9j.js → child-DzZ-aI6k.js} +130 -2
  5. package/lib/client.js +17093 -2269
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/dev-context-Bdm-eVer.js +40 -0
  9. package/lib/doctor.js +5 -3
  10. package/lib/{gallery-BWHmjogd.js → gallery-Ctz-UoFk.js} +3 -3
  11. package/lib/{generator-QCdm8nUh.js → generator-Cv6WWmZT.js} +2 -2
  12. package/lib/helper.js +15 -1
  13. package/lib/{hooks-C2U1-8ur.js → hooks-BdR3mBeM.js} +751 -344
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +342 -463
  16. package/lib/jail-Cp4zEfip.js +107 -0
  17. package/lib/{library-4zmCAshR.js → library-BU2A_Dx8.js} +3 -3
  18. package/lib/{lorebook-author-tools-Bjfjt3bg.js → lorebook-author-tools-DUKcQu8P.js} +20 -7
  19. package/lib/lorebook-authoring.js +12 -5
  20. package/lib/{narration-b_VBEUWn.js → narration-CDsJ5wxH.js} +29 -2
  21. package/lib/orchestration.js +615 -48
  22. package/lib/{pack-jail-Ci9bIeDI.js → pack-jail-CzHQu0n3.js} +559 -23
  23. package/lib/{packs-CYkozh8Q.js → packs-BZ-45J4-.js} +2 -2
  24. package/lib/{presenter-agent-CqkAL03Q.js → presenter-agent-C2ZkoxZu.js} +9 -9
  25. package/lib/{preset-B-35yUmt.js → preset-BPnRPW-1.js} +4 -4
  26. package/lib/{preset-author-tools-BUymqZM5.js → preset-author-tools-DBqPwn-o.js} +9 -8
  27. package/lib/preset-authoring.js +11 -6
  28. package/lib/{reflection-B9N0z3KY.js → reflection-Cuy0YLv0.js} +22 -16
  29. package/lib/{presets-_U-xroo0.js → serial-BZNeK57v.js} +1305 -331
  30. package/lib/service-mRKwpWjX.js +140 -0
  31. package/lib/{text-C2AGl7Je.js → text-Dfv8S8eq.js} +27 -2
  32. package/lib/{turn-guard-C0M3rXEN.js → turn-guard-xaFxYc1T.js} +3 -3
  33. package/locale/de.json +6 -0
  34. package/locale/en.json +6 -0
  35. package/locale/es.json +6 -0
  36. package/locale/fr.json +6 -0
  37. package/locale/ja.json +6 -0
  38. package/locale/pt.json +6 -0
  39. package/locale/ru.json +6 -0
  40. package/locale/zh.json +6 -0
  41. package/package.json +34 -34
  42. package/prompts/en/import/finish-ok.md +1 -1
  43. package/prompts/en/import/generator.md +1 -1
  44. package/prompts/en/import/style.md +2 -1
  45. package/prompts/en/import/variables.md +2 -1
  46. package/prompts/en/roleplay/character-lookup.md +1 -1
  47. package/prompts/en/roleplay/decide-errand.md +1 -0
  48. package/prompts/en/roleplay/decide-message.md +1 -0
  49. package/prompts/en/roleplay/dream.md +1 -0
  50. package/prompts/en/roleplay/gate-repeat.md +1 -0
  51. package/prompts/en/world/procedure.md +1 -1
  52. package/prompts/zh/import/finish-ok.md +1 -1
  53. package/prompts/zh/import/generator.md +1 -1
  54. package/prompts/zh/import/style.md +2 -1
  55. package/prompts/zh/import/variables.md +2 -1
  56. package/prompts/zh/roleplay/character-lookup.md +1 -1
  57. package/prompts/zh/roleplay/decide-errand.md +1 -0
  58. package/prompts/zh/roleplay/decide-message.md +1 -0
  59. package/prompts/zh/roleplay/dream.md +1 -0
  60. package/prompts/zh/roleplay/gate-repeat.md +1 -0
  61. package/prompts/zh/world/procedure.md +1 -1
@@ -1,16 +1,19 @@
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 silenceHarnessDevContext } from "./dev-context-Bdm-eVer.js";
2
+ import { t as promptFor } from "./access-DifaiHrI.js";
3
+ 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-BdR3mBeM.js";
4
+ 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-DzZ-aI6k.js";
5
+ import { a as whereabouts, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-Cuy0YLv0.js";
6
+ import { A as routeVerdicts, E as askYesNo, Mt as splitPanels, O as modeFor, T as announceProblem, fn as INTENT_STATUSES, j as yesAt, k as noAt, n as STANDING_PROMPT, sn as guarded } from "./serial-BZNeK57v.js";
7
+ import { i as translator, r as languageOf$1 } from "./text-Dfv8S8eq.js";
8
+ import { a as liveSettings, g as GATE_SITES, n as encodeOutput } from "./narration-CDsJ5wxH.js";
9
+ import { t as registerFoldersJail } from "./jail-Cp4zEfip.js";
10
+ import { a as workspaceOf, n as storyRoots } from "./service-mRKwpWjX.js";
11
+ import { C as slug, T as uniqueKey, t as addToLibrary } from "./library-BU2A_Dx8.js";
12
+ import { _ as API_PREFIX } from "./packs-BZ-45J4-.js";
13
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-Ctz-UoFk.js";
14
+ import { c as presentedFor, i as findImages, n as interpretImage, s as present, t as runImagePresenter } from "./presenter-agent-C2ZkoxZu.js";
12
15
  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";
16
+ 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
17
  import { existsSync } from "node:fs";
15
18
  import { createHash } from "node:crypto";
16
19
  import { readdir } from "node:fs/promises";
@@ -192,7 +195,7 @@ function describePrompt(job, memory) {
192
195
  ...records.open_threads.length === 0 ? ["- none"] : records.open_threads.map((thread) => `- id ${thread.id}: ${thread.text}`)
193
196
  ].join("\n");
194
197
  }
195
- const RESULT$4 = {
198
+ const RESULT$5 = {
196
199
  type: "object",
197
200
  properties: {
198
201
  complete: {
@@ -339,7 +342,7 @@ function recordKeeper(deps) {
339
342
  prompt: describePrompt(job, memory),
340
343
  tools: keeperTools(job, memory, progress),
341
344
  external: externalGiven(parent.ctx.tools, job.store.settings().tools, "records"),
342
- result: RESULT$4,
345
+ result: RESULT$5,
343
346
  beforeSubmit: () => {
344
347
  if (progress.edits === 0 && !warned && job.store.story.records({ rounds: job.rounds.map(({ turn, round }) => ({
345
348
  turn,
@@ -370,7 +373,7 @@ function suggestionProblems(lines, wanted) {
370
373
  /** One short line each: whitespace is collapsed. */
371
374
  const tidySuggestions = (lines) => lines.map((line) => line.trim().replace(/\s+/g, " "));
372
375
  // src/host/orchestration/suggester.ts
373
- const RESULT$3 = {
376
+ const RESULT$4 = {
374
377
  type: "object",
375
378
  properties: { options: {
376
379
  type: "array",
@@ -412,7 +415,7 @@ function suggestionWriter(deps) {
412
415
  trace: childTrace(job.store, "suggestions", "suggestions"),
413
416
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
414
417
  prompt: promptOf(job),
415
- result: RESULT$3,
418
+ result: RESULT$4,
416
419
  structured: true,
417
420
  beforeSubmit: (value) => {
418
421
  const problems = suggestionProblems(wanted(value.options, job.count), job.count);
@@ -424,7 +427,7 @@ function suggestionWriter(deps) {
424
427
  } };
425
428
  }
426
429
  // src/host/triggers/judge.ts
427
- const RESULT$2 = {
430
+ const RESULT$3 = {
428
431
  type: "object",
429
432
  properties: { verdicts: {
430
433
  type: "array",
@@ -454,7 +457,7 @@ const RESULT$2 = {
454
457
  additionalProperties: false
455
458
  };
456
459
  /** 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;
460
+ const REASON_CHARS$2 = 600;
458
461
  /** The statements of the triggers still waiting, each once. */
459
462
  function waitingStatements(job) {
460
463
  return [...new Set(job.store.story.triggers.list({ status: "dormant" }).flatMap((trigger) => judgedStatements(trigger.condition)))];
@@ -503,7 +506,7 @@ function triggerJudge(deps) {
503
506
  turn: job.turn,
504
507
  reasoningEffort: settings.reasoning.children,
505
508
  sampling: childSampling(settings, "records", estimateAnswer(subset.flatMap(() => [
506
- REASON_CHARS$1,
509
+ REASON_CHARS$2,
507
510
  0,
508
511
  0
509
512
  ]), settings.prompts.language)),
@@ -511,7 +514,7 @@ function triggerJudge(deps) {
511
514
  trace: childTrace(store, "records", "trigger judge"),
512
515
  persona: promptFor(parent, "roleplay/trigger-judge", settings.prompts.language),
513
516
  prompt: brief$2(scene, subset),
514
- result: RESULT$2,
517
+ result: RESULT$3,
515
518
  beforeSubmit: (value) => {
516
519
  const numbers = value.verdicts.map((verdict) => verdict.number);
517
520
  const missing = subset.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
@@ -633,6 +636,105 @@ function ruleChecks(deps) {
633
636
  return found.map((key) => rules[Number(key.slice(4))]);
634
637
  } };
635
638
  }
639
+ // src/host/decisions/repeats.ts
640
+ const PROMPT$1 = "roleplay/gate-repeat";
641
+ const REASON_CHARS$1 = 300;
642
+ const GATE_BAND$1 = .15;
643
+ const sentencesOf = (text) => text.split(/\n+|(?<=[.!?。!?…])\s*/).map((sentence) => sentence.trim()).filter((sentence) => sentence !== "");
644
+ const keyOf$1 = (sentence) => sentence.toLowerCase().replace(/\s+/g, " ");
645
+ /** 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. */
646
+ function repeatedSentences(narration, earlier, minChars) {
647
+ const told = new Set(earlier.flatMap((text) => sentencesOf(text).map(keyOf$1)));
648
+ const found = /* @__PURE__ */ new Map();
649
+ for (const sentence of sentencesOf(narration)) {
650
+ const key = keyOf$1(sentence);
651
+ if (key.length < minChars) continue;
652
+ if (told.has(key) && !found.has(key)) found.set(key, sentence);
653
+ told.add(key);
654
+ }
655
+ return [...found.values()];
656
+ }
657
+ const RESULT$2 = {
658
+ type: "object",
659
+ properties: {
660
+ reason: {
661
+ type: "string",
662
+ 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."
663
+ },
664
+ stale: {
665
+ type: "array",
666
+ items: { type: "integer" },
667
+ description: "The numbers of the sentences that are stale filler; empty when every repeat is meant."
668
+ }
669
+ },
670
+ required: ["reason", "stale"],
671
+ additionalProperties: false
672
+ };
673
+ const asFinding = (stale) => stale.length === 0 ? [] : [{
674
+ gate: "repeats",
675
+ 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`
676
+ }];
677
+ /**
678
+ * 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
679
+ * 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.
680
+ */
681
+ async function repeatFindings(job, deps, signal) {
682
+ const settings = job.store.settings();
683
+ const mode = settings.decisions.repeats;
684
+ if (mode === "off" || job.narration.trim() === "") return [];
685
+ const earlier = deps.earlier(job.chat, settings.decisions.repeatTurns);
686
+ const candidates = repeatedSentences(job.narration, earlier, settings.decisions.repeatChars).slice(0, 6);
687
+ if (candidates.length === 0) return [];
688
+ if (mode === "strict") return asFinding(candidates);
689
+ const keys = candidates.map((_, index) => `repeat${index}`);
690
+ const shown = (sentence) => earlier.filter((text) => text.toLowerCase().includes(sentence.toLowerCase())).join("\n").slice(-1500);
691
+ try {
692
+ const routed = await routeVerdicts({
693
+ mode,
694
+ yesAt: settings.decisions.gateThreshold,
695
+ noAt: Math.max(0, settings.decisions.gateThreshold - GATE_BAND$1),
696
+ turn: job.turn,
697
+ keys,
698
+ what: (key) => candidates[Number(key.slice(6))],
699
+ probabilities: async () => {
700
+ const service = deps.decisions?.();
701
+ if (service === void 0) throw new Error("no decision service is selected, or the selected one is not loaded");
702
+ const state = {
703
+ narration: job.narration,
704
+ earlier_turns: earlier.join("\n").slice(-1500)
705
+ };
706
+ return await askYesNo(service, state, candidates.map((sentence, index) => ({
707
+ key: keys[index],
708
+ instructions: job.store.text(PROMPT$1, { sentence })
709
+ })), signal);
710
+ },
711
+ llm: async () => {
712
+ const parent = deps.agentOf(job.chat);
713
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
714
+ const answer = await runChild({
715
+ parent,
716
+ signal,
717
+ reasoningEffort: settings.reasoning.children,
718
+ sampling: childSampling(settings, "records", estimateAnswer([REASON_CHARS$1, 0], settings.prompts.language)),
719
+ ...childModel(settings, "records"),
720
+ trace: childTrace(job.store, "records", "repeats check"),
721
+ 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.`,
722
+ 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")}`,
723
+ result: RESULT$2,
724
+ maxCalls: 2
725
+ });
726
+ return new Map(keys.map((key, index) => [key, answer.stale.includes(index + 1)]));
727
+ }
728
+ }, signal);
729
+ announceProblem(deps.seen, `${job.chat}:repeats`, routed.report, deps.problem);
730
+ job.store.recordDecisions?.("repeats", routed.report);
731
+ return asFinding(candidates.filter((_, index) => routed.verdicts.get(keys[index]) === true));
732
+ } catch (error) {
733
+ if (signal.aborted) throw error;
734
+ 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)}`);
735
+ return [];
736
+ }
737
+ }
636
738
  // src/host/decisions/gates.ts
637
739
  /**
638
740
  * 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 +790,7 @@ function outputGates(deps) {
688
790
  return { async check(job, signal) {
689
791
  const settings = job.store.settings();
690
792
  const parent = deps.agentOf(job.chat);
691
- return [...(await Promise.all(GATE_SITES.map(async (site) => {
793
+ const found = await Promise.all(GATE_SITES.map(async (site) => {
692
794
  const mode = settings.decisions[site];
693
795
  const gate = GATES[site];
694
796
  if (mode === "off" || !gate.applies(job)) return [];
@@ -737,7 +839,19 @@ function outputGates(deps) {
737
839
  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
840
  return [];
739
841
  }
740
- }))).flat(), ...await secretFindings(job, settings.decisions, deps.decisions?.(), seen, signal, deps.problem)];
842
+ }));
843
+ const repeats = await repeatFindings(job, {
844
+ agentOf: deps.agentOf,
845
+ ...deps.decisions === void 0 ? {} : { decisions: deps.decisions },
846
+ earlier: deps.earlier ?? (() => []),
847
+ seen,
848
+ ...deps.problem === void 0 ? {} : { problem: deps.problem }
849
+ }, signal);
850
+ return [
851
+ ...found.flat(),
852
+ ...repeats,
853
+ ...await secretFindings(job, settings.decisions, deps.decisions?.(), seen, signal, deps.problem)
854
+ ];
741
855
  } };
742
856
  }
743
857
  const SECRET_PROMPT = "roleplay/gate-secret";
@@ -761,7 +875,7 @@ async function secretFindings(job, decisions, service, seen, signal, say) {
761
875
  /** 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
876
  const BAND = .15;
763
877
  /** What the models are shown of the turn, in characters: enough for what happened, never the whole story. */
764
- const NARRATION_CHARS = 2400;
878
+ const NARRATION_CHARS$1 = 2400;
765
879
  const DEEDS_CHARS = 2400;
766
880
  /** 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
881
  const verdictSchema = (keys) => ({
@@ -829,9 +943,9 @@ function question(store, item, tr) {
829
943
  function brief$1(job, items, tr, heading) {
830
944
  const range = (def) => def.kind === "number" ? ` (${def.min ?? "…"} to ${def.max ?? "…"}${def.integer ? ", whole numbers" : ""})` : def.kind === "choice" ? ` (${def.options.join(", ")})` : "";
831
945
  return [
832
- job.input.trim() === "" ? void 0 : `${tr("What the player wrote:")}\n${job.input.slice(0, NARRATION_CHARS)}`,
946
+ job.input.trim() === "" ? void 0 : `${tr("What the player wrote:")}\n${job.input.slice(0, NARRATION_CHARS$1)}`,
833
947
  `${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)}`,
948
+ `${tr("What the player read:")}\n${job.narration.slice(0, NARRATION_CHARS$1)}`,
835
949
  `${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
950
  ].filter((part) => part !== void 0).join("\n\n");
837
951
  }
@@ -849,7 +963,7 @@ function variableTracker(deps) {
849
963
  const items = trackedItems(job.store, `${job.input}\n${job.deeds.join("\n")}\n${job.narration}`);
850
964
  if (items.length === 0) return 0;
851
965
  const parent = deps.agentOf(job.chat);
852
- const tr = translator(languageOf(settings.prompts.language));
966
+ const tr = translator(languageOf$1(settings.prompts.language));
853
967
  const byKey = new Map(items.map((item) => [item.key, item]));
854
968
  const personaOf = (id) => parent === void 0 ? job.store.text(id) : promptFor(parent, id, settings.prompts.language);
855
969
  const ask = async (persona, prompt, result, answers, label) => {
@@ -888,7 +1002,7 @@ function variableTracker(deps) {
888
1002
  if (service === void 0) throw new Error("no decision service is selected, or the selected one is not loaded");
889
1003
  const state = {
890
1004
  happened: job.deeds.join("\n").slice(0, DEEDS_CHARS),
891
- narration: job.narration.slice(0, NARRATION_CHARS),
1005
+ narration: job.narration.slice(0, NARRATION_CHARS$1),
892
1006
  ...job.input.trim() === "" ? {} : { player_wrote: job.input }
893
1007
  };
894
1008
  return await askYesNo(service, state, keys.map((key) => ({
@@ -945,6 +1059,57 @@ function variableTracker(deps) {
945
1059
  }
946
1060
  } };
947
1061
  }
1062
+ // src/host/decisions/errands.ts
1063
+ /** At most this many characters are asked about in one request, and the narration is cut to this many characters. */
1064
+ const MAX_ASKED = 6;
1065
+ const NARRATION_CHARS = 1500;
1066
+ const PROMPT = "roleplay/decide-errand";
1067
+ /** The characters a turn's words name that could be kept: awake, not the player's, and not already off their day. */
1068
+ function named(store, turn, text) {
1069
+ const lower = text.toLowerCase();
1070
+ return store.cast().flatMap((member) => {
1071
+ const { character } = member;
1072
+ if (character.control === "player" || character.kind !== "person" || store.asleep(turn, character.id) !== void 0) return [];
1073
+ if (store.agenda(turn, character.id).offDay !== void 0) return [];
1074
+ return [character.name, ...character.aliases ?? []].some((name) => name.trim() !== "" && lower.includes(name.toLowerCase())) ? [{
1075
+ id: character.id,
1076
+ key: member.key,
1077
+ name: character.name
1078
+ }] : [];
1079
+ }).slice(0, MAX_ASKED);
1080
+ }
1081
+ /**
1082
+ * 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
1083
+ * 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
1084
+ * 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.
1085
+ */
1086
+ function errandChecks(deps) {
1087
+ const seen = /* @__PURE__ */ new Map();
1088
+ return { async keep(job, signal) {
1089
+ const { store } = job;
1090
+ const settings = store.settings();
1091
+ if (settings.decisions.errands === "off" || !settings.schedule.enabled || store.holdForPlayer === void 0) return 0;
1092
+ const narration = job.narration.slice(0, NARRATION_CHARS);
1093
+ const candidates = named(store, job.turn, [
1094
+ job.input,
1095
+ narration,
1096
+ ...job.deeds
1097
+ ].join("\n"));
1098
+ if (candidates.length === 0) return 0;
1099
+ const asks = candidates.map((candidate) => ({
1100
+ key: candidate.key,
1101
+ instructions: store.text(PROMPT, { name: candidate.name })
1102
+ }));
1103
+ const { found, report } = await askExtra(deps.decisions?.(), {
1104
+ player_message: job.input,
1105
+ what_happened: job.deeds,
1106
+ what_the_player_read: narration
1107
+ }, asks, settings.decisions.gateThreshold, signal);
1108
+ noteExtra("errands", job.chat, store, report, seen, deps.problem);
1109
+ for (const key of found) store.holdForPlayer(candidates.find((candidate) => candidate.key === key).id);
1110
+ return found.length;
1111
+ } };
1112
+ }
948
1113
  // src/host/factions/strategist.ts
949
1114
  const LAST_KEY = "strategy.last";
950
1115
  const DAY_MS = 864e5;
@@ -1588,6 +1753,168 @@ var RollReplay = class {
1588
1753
  };
1589
1754
  }
1590
1755
  };
1756
+ // src/host/orchestration/autonomy.ts
1757
+ /** The longest message a character leaves: it is a note beside the story, not a scene. */
1758
+ const MAX_MESSAGE_CHARS = 500;
1759
+ const MINUTE$1 = 6e4;
1760
+ const seenProblems = /* @__PURE__ */ new Map();
1761
+ const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
1762
+ /** 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. */
1763
+ function writingChance(store, member, player, turn, idleMs) {
1764
+ const { character } = member;
1765
+ if (character.control !== "agent" || character.kind !== "person" || character.tier === "background") return void 0;
1766
+ if (member.place !== void 0 && member.place.location.id === player.place?.location.id) return void 0;
1767
+ if (store.agenda(turn, character.id).now?.interruptible === false) return void 0;
1768
+ if (store.asleep(turn, character.id) !== void 0) return void 0;
1769
+ const relation = store.story.relationships.get(character.id, player.character.id);
1770
+ if (relation === void 0) return void 0;
1771
+ return clamp(.15 + .35 * clamp(relation.affinity, 0, 1) + .2 * Math.min(1, idleMs / (720 * MINUTE$1)), 0, .9);
1772
+ }
1773
+ /**
1774
+ * 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
1775
+ * 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
1776
+ * 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.
1777
+ */
1778
+ async function tickAutonomy(deps, chat, signal) {
1779
+ const store = deps.stores(chat);
1780
+ const autonomy = store?.autonomy;
1781
+ if (store === void 0 || autonomy === void 0) return {
1782
+ outcome: "off",
1783
+ moved: 0
1784
+ };
1785
+ const settings = store.settings();
1786
+ if (!settings.autonomy.enabled || settings.clock.mode !== "real") return {
1787
+ outcome: "off",
1788
+ moved: 0
1789
+ };
1790
+ if (deps.engine.playing(chat)) return {
1791
+ outcome: "busy",
1792
+ moved: 0
1793
+ };
1794
+ const turn = store.story.metadata.get().turns;
1795
+ const moved = autonomy.catchUp(turn).length;
1796
+ const shifted = autonomy.shifts();
1797
+ if (!settings.autonomy.messages) return {
1798
+ outcome: "quiet",
1799
+ moved
1800
+ };
1801
+ const config = settings.autonomy;
1802
+ const now = deps.wall();
1803
+ const state = autonomy.state();
1804
+ const last = autonomy.lastPlayerAt();
1805
+ if (state.unanswered >= config.maxUnanswered) return {
1806
+ outcome: "limit",
1807
+ moved
1808
+ };
1809
+ if (last === void 0 || now - last < config.idleMinutes * MINUTE$1) return {
1810
+ outcome: "recent",
1811
+ moved
1812
+ };
1813
+ if (now - last > config.awayHours * 60 * MINUTE$1) return {
1814
+ outcome: "away",
1815
+ moved
1816
+ };
1817
+ const cast = store.cast();
1818
+ const player = cast.find((member) => member.character.control === "player");
1819
+ if (player === void 0) return {
1820
+ outcome: "nobody",
1821
+ moved
1822
+ };
1823
+ const draw = deps.draw ?? seededRoll;
1824
+ const gap = config.messageGapMinutes * MINUTE$1;
1825
+ const eligible = cast.flatMap((member) => {
1826
+ if (now - (state.sent[member.key] ?? 0) < gap) return [];
1827
+ const chance = writingChance(store, member, player, turn, now - last);
1828
+ return chance === void 0 ? [] : [{
1829
+ member,
1830
+ chance
1831
+ }];
1832
+ });
1833
+ if (eligible.length === 0) return {
1834
+ outcome: "nobody",
1835
+ moved
1836
+ };
1837
+ const transition = eligible.filter((entry) => shifted.includes(entry.member.key) && draw(`${chat}:${entry.member.key}:shift:${now}`) < config.transitionChance);
1838
+ if (!(draw(`${chat}:look:${now}`) < config.chance * config.decay ** state.unanswered) && transition.length === 0) return {
1839
+ outcome: "idle",
1840
+ moved
1841
+ };
1842
+ const pool = transition.length > 0 ? transition : eligible;
1843
+ const total = pool.reduce((sum, entry) => sum + entry.chance, 0);
1844
+ let pick = draw(`${chat}:pick:${now}`) * total;
1845
+ const speaker = (pool.find((entry) => {
1846
+ pick -= entry.chance;
1847
+ return pick < 0;
1848
+ }) ?? pool[pool.length - 1]).member;
1849
+ const because = transition.some((entry) => entry.member === speaker);
1850
+ if (settings.decisions.messages === "on") {
1851
+ const time = store.time(turn);
1852
+ const asks = [{
1853
+ key: "write",
1854
+ instructions: store.text("roleplay/decide-message", {})
1855
+ }];
1856
+ const facts = {
1857
+ character: speaker.character.name,
1858
+ doing: store.agenda(turn, speaker.character.id).now?.activity ?? speaker.character.name,
1859
+ day_just_changed: because,
1860
+ hours_the_player_has_been_away: Math.round((now - last) / (60 * MINUTE$1) * 10) / 10,
1861
+ unanswered_messages: state.unanswered,
1862
+ time_of_day: describeInstant(time.now, time.zone)
1863
+ };
1864
+ const { found, report } = await askExtra(deps.decisions?.(), facts, asks, settings.decisions.gateThreshold, signal);
1865
+ noteExtra("messages", chat, store, report, seenProblems, deps.problem);
1866
+ if (report.problem === void 0 && found.length === 0) return {
1867
+ outcome: "declined",
1868
+ moved
1869
+ };
1870
+ }
1871
+ const parent = deps.agentOf(chat);
1872
+ if (parent === void 0) return {
1873
+ outcome: "off",
1874
+ moved
1875
+ };
1876
+ const language = languageOf(settings.prompts.language) === "zh" ? "zh" : "en";
1877
+ const tr = translator(language);
1878
+ const time = store.time(turn);
1879
+ const situation = [
1880
+ tr("The player's character has not been with you for {away}, and you are not with them now. It is {now} for you.", {
1881
+ away: describeDuration(now - last, language),
1882
+ now: describeInstant(time.now, time.zone, language)
1883
+ }),
1884
+ 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."),
1885
+ because ? tr("Something in your own day has just changed, and it may have made you think of them.") : "",
1886
+ 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.") : "",
1887
+ tr("If nothing makes you want to write now, answer with commitment low and no utterance.")
1888
+ ].filter((line) => line !== "").join(" ");
1889
+ const run = characterRunner({
1890
+ parent,
1891
+ boundaries: deps.boundaries,
1892
+ store
1893
+ });
1894
+ const report = await deps.engine.askAlone({
1895
+ chat,
1896
+ turn
1897
+ }, speaker.key, situation, run, signal);
1898
+ const text = report?.utterance?.trim().replace(/^["“「]|["”」]$/g, "").trim();
1899
+ if (report === void 0 || report.commitment === "low" || text === void 0 || text === "" || text.length > MAX_MESSAGE_CHARS || wrongLanguage(language, { message: text }, { strays: true }) !== void 0) {
1900
+ autonomy.asked(speaker.key, now);
1901
+ return {
1902
+ outcome: "quiet",
1903
+ moved
1904
+ };
1905
+ }
1906
+ autonomy.said(turn, {
1907
+ at: now,
1908
+ character: speaker.key,
1909
+ name: speaker.character.name,
1910
+ text
1911
+ });
1912
+ return {
1913
+ outcome: "wrote",
1914
+ moved,
1915
+ message: text
1916
+ };
1917
+ }
1591
1918
  // src/host/orchestration/check-tool.ts
1592
1919
  const CHECK_NARRATE_TOOL = "roll_and_narrate";
1593
1920
  const BRANCHES = [
@@ -1881,7 +2208,7 @@ function rerankMemories(deps) {
1881
2208
  * someone to talk to, a way out, a thing to look at, then plain standbys. No model is asked.
1882
2209
  */
1883
2210
  function fallbackSuggestions(store, count) {
1884
- const tr = translator(languageOf(store.settings().prompts.language));
2211
+ const tr = translator(languageOf$1(store.settings().prompts.language));
1885
2212
  const player = store.cast().find((member) => member.character.control === "player");
1886
2213
  const view = player?.place === void 0 ? void 0 : store.place(player.place.location.id);
1887
2214
  const people = (view?.here ?? []).filter((member) => member.character.id !== player?.character.id).map((member) => tr("Talk to {name}.", { name: member.character.name }));
@@ -1921,11 +2248,13 @@ var AfterTurnJobs = class {
1921
2248
  reflecting = /* @__PURE__ */ new Set();
1922
2249
  casting = /* @__PURE__ */ new Set();
1923
2250
  tracking = /* @__PURE__ */ new Set();
2251
+ erranding = /* @__PURE__ */ new Set();
1924
2252
  constructor(deps) {
1925
2253
  this.deps = deps;
1926
2254
  }
1927
2255
  start(owner, cancel, facts) {
1928
2256
  if (facts !== void 0) this.trackVariables(owner, cancel, facts);
2257
+ if (facts !== void 0) this.keepErrands(owner, cancel, facts);
1929
2258
  this.consolidate(owner, cancel);
1930
2259
  this.strategize(owner, cancel);
1931
2260
  this.judge(owner, cancel);
@@ -1951,6 +2280,24 @@ var AfterTurnJobs = class {
1951
2280
  this.tracking.delete(owner.chat);
1952
2281
  }));
1953
2282
  }
2283
+ /** Characters the story told or left to wait for the player are kept where they are until the player comes to them. */
2284
+ keepErrands(owner, cancel, facts) {
2285
+ const store = this.deps.stores(owner.chat);
2286
+ if (store === void 0 || store.settings().decisions.errands === "off" || this.erranding.has(owner.chat)) return;
2287
+ this.erranding.add(owner.chat);
2288
+ this.deps.track(owner.chat, this.deps.boundaries().errandKeeper.keep({
2289
+ chat: owner.chat,
2290
+ turn: owner.turn,
2291
+ store,
2292
+ ...facts
2293
+ }, cancel).then((kept) => {
2294
+ if (kept > 0) this.deps.written(owner.chat);
2295
+ }).catch((error) => {
2296
+ if (!cancel.aborted) this.deps.problem(`who waits for the player was not looked at: ${messageOf(error)}`);
2297
+ }).finally(() => {
2298
+ this.erranding.delete(owner.chat);
2299
+ }));
2300
+ }
1954
2301
  /** Whether a reflection is running for the chat. */
1955
2302
  isReflecting(chat) {
1956
2303
  return this.reflecting.has(chat);
@@ -2179,7 +2526,7 @@ function explainPhase(state, attempted) {
2179
2526
  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
2527
  const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
2181
2528
  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";
2529
+ 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
2530
  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
2531
  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
2532
  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 +2729,7 @@ async function askCharacters(deps, owner, number, keys, cast, state, run, signal
2382
2729
  text: (id, variables) => deps.storeOf(owner).text(id, variables),
2383
2730
  ...time === void 0 ? {} : { time },
2384
2731
  ...agenda === void 0 ? {} : { agenda },
2732
+ ...state.dreaming === key ? { dreaming: true } : {},
2385
2733
  ...cues.length === 0 ? {} : { cues },
2386
2734
  ...upcoming.length === 0 ? {} : { upcoming },
2387
2735
  ...tracked === void 0 || tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
@@ -2435,6 +2783,13 @@ async function askCharacters(deps, owner, number, keys, cast, state, run, signal
2435
2783
  };
2436
2784
  }
2437
2785
  // src/host/orchestration/round-record.ts
2786
+ /** 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. */
2787
+ function holds(member, outcome, check, state, store, turn) {
2788
+ if (member.character.control === "player") return false;
2789
+ if (outcome.offRoutineMinutes !== void 0 || outcome.waitsForPlayer === true) return true;
2790
+ if (check?.ok === true && check.plan.from !== check.move.to) return true;
2791
+ return state.dreaming !== member.key && store.asleep(turn, member.character.id) !== void 0;
2792
+ }
2438
2793
  /** 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
2794
  function recordRound(store, owner, state, fire) {
2440
2795
  const decided = decisions(state);
@@ -2481,6 +2836,10 @@ function recordRound(store, owner, state, fire) {
2481
2836
  ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() }
2482
2837
  },
2483
2838
  ...check?.ok === true ? { move: check.move } : {},
2839
+ ...holds(member, outcome, check, state, store, owner.turn) ? { hold: {
2840
+ ...outcome.offRoutineMinutes === void 0 ? {} : { minutes: outcome.offRoutineMinutes },
2841
+ ...outcome.waitsForPlayer === true ? { untilPlayer: true } : {}
2842
+ } } : {},
2484
2843
  ...outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 ? {} : { items: outcome.itemChanges }
2485
2844
  }
2486
2845
  }];
@@ -2758,7 +3117,30 @@ function asSpoken(segments, spoken) {
2758
3117
  * 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
3118
  * A refusal is thrown for the game master to correct; past `MAX_REFUSALS`, or when `silent`, the output is repaired instead.
2760
3119
  */
2761
- function checkedOutput(narrationChecker, language, state, segments, silent) {
3120
+ /** 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. */
3121
+ function withoutPanels(segments) {
3122
+ let found = false;
3123
+ return {
3124
+ segments: segments.flatMap((segment) => {
3125
+ if (segment.type !== "narration") return [segment];
3126
+ const { prose, panels } = splitPanels(segment.text, { alone: true });
3127
+ if (panels.length === 0) return [segment];
3128
+ found = true;
3129
+ return prose === "" ? [] : [{
3130
+ ...segment,
3131
+ text: prose
3132
+ }];
3133
+ }),
3134
+ found
3135
+ };
3136
+ }
3137
+ function checkedOutput(narrationChecker, language, state, delivered, silent) {
3138
+ const cleaned = withoutPanels(delivered);
3139
+ if (cleaned.found && !silent && state.refused < 2) {
3140
+ state.refused += 1;
3141
+ 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");
3142
+ }
3143
+ const segments = cleaned.segments;
2762
3144
  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
3145
  const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") }, { strays: true });
2764
3146
  if (problems.length === 0 && wording !== void 0 && !silent && state.refused < 2) {
@@ -2767,7 +3149,7 @@ function checkedOutput(narrationChecker, language, state, segments, silent) {
2767
3149
  }
2768
3150
  if (problems.length === 0) return {
2769
3151
  segments: asSpoken(segments, state.utterances),
2770
- repaired: false
3152
+ repaired: cleaned.found
2771
3153
  };
2772
3154
  state.refused += 1;
2773
3155
  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 +3215,10 @@ async function runOffScene(deps, owner, state, store, due, limit) {
2833
3215
  return member === void 0 ? [] : [{
2834
3216
  character: member.character.id,
2835
3217
  patch: { activity: report.intent },
2836
- ...move?.ok === true ? { move: move.move } : {}
3218
+ ...move?.ok === true ? {
3219
+ move: move.move,
3220
+ hold: {}
3221
+ } : {}
2837
3222
  }];
2838
3223
  }));
2839
3224
  state.offstage += 1;
@@ -2876,7 +3261,11 @@ async function runOffScene(deps, owner, state, store, due, limit) {
2876
3261
  }
2877
3262
  }
2878
3263
  // src/host/orchestration/turn-engine.ts
3264
+ /** Asks one character to act; what the game master calls a character is the character's key. */
3265
+ /** Told to the game master when it asks again in a dream the harness has already asked. */
3266
+ 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
3267
  const MAX_OBJECTIONS = 3;
3268
+ const MAX_PREVIEW_REFUSALS = 3;
2880
3269
  /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
2881
3270
  const MAX_ROUND_SECONDS = 86400;
2882
3271
  /** 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 +3298,8 @@ var TurnEngine = class {
2909
3298
  reflectionCancels = /* @__PURE__ */ new Map();
2910
3299
  /** Chats whose characters away from the player are being asked about what fell due: one run at a time. */
2911
3300
  offstage = /* @__PURE__ */ new Set();
3301
+ /** 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. */
3302
+ observe;
2912
3303
  constructor(boundaries, stores, problem = () => void 0, written = () => void 0) {
2913
3304
  this.boundaries = boundaries;
2914
3305
  this.stores = stores;
@@ -2932,6 +3323,30 @@ var TurnEngine = class {
2932
3323
  * 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
3324
  * 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
3325
  */
3326
+ /** The turn is the player's visit to the dream of a sleeping character: the sleeper may be asked, and stays asleep. */
3327
+ beginDream(owner, key, situation) {
3328
+ const state = this.stateFor(owner);
3329
+ state.dreaming = key;
3330
+ state.dreamSituation = situation;
3331
+ }
3332
+ /**
3333
+ * The harness asks the sleeper itself, so that a dream never depends on the game master choosing the right tools: the answer is
3334
+ * returned for the game master to narrate and no round is recorded, because nothing in a dream changes the waking world.
3335
+ * Nothing is returned when the sleeper could not answer, and the game master then asks as in any turn.
3336
+ */
3337
+ async dream(owner, run) {
3338
+ const state = this.stateFor(owner);
3339
+ const key = state.dreaming;
3340
+ if (key === void 0) return void 0;
3341
+ const store = this.storeOf(owner);
3342
+ state.situation = state.dreamSituation ?? "";
3343
+ state.cast = store.cast();
3344
+ const report = (await this.ask(owner, 1, [key], state.cast, state, run, state.cancel.signal)).reports[0];
3345
+ if (report === void 0) return void 0;
3346
+ state.dreamed = true;
3347
+ state.phase = "between";
3348
+ return report;
3349
+ }
2935
3350
  beginOoc(owner, request, question = false) {
2936
3351
  const state = this.stateFor(owner);
2937
3352
  state.ooc = {
@@ -2987,7 +3402,7 @@ var TurnEngine = class {
2987
3402
  * 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
3403
  * @throws {Error} when the turn is not an ordinary one, was already judged, the reason is empty, or `at` is not a place.
2989
3404
  */
2990
- judge(owner, allowed, reason, at, uncertain) {
3405
+ judge(owner, allowed, reason, at, uncertain, goesTo) {
2991
3406
  const state = this.stateFor(owner);
2992
3407
  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
3408
  if (state.phase !== "idle") throw new Error("the action is judged first, before anything else");
@@ -3012,9 +3427,16 @@ var TurnEngine = class {
3012
3427
  };
3013
3428
  }
3014
3429
  }
3430
+ const destination = goesTo?.trim() ?? "";
3431
+ if (destination !== "") {
3432
+ const store = this.storeOf(owner);
3433
+ const player = store.cast().find((member) => member.character.control === "player");
3434
+ 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`);
3435
+ }
3015
3436
  state.judgement = {
3016
3437
  allowed,
3017
- reason: why
3438
+ reason: why,
3439
+ ...allowed && destination !== "" ? { goesTo: destination } : {}
3018
3440
  };
3019
3441
  const { tools } = this.storeOf(owner).settings();
3020
3442
  if (allowed && uncertain === true && (toolEnabled(tools, "gameMaster", "roll_check") || toolEnabled(tools, "gameMaster", "roll_dice"))) {
@@ -3065,11 +3487,12 @@ var TurnEngine = class {
3065
3487
  */
3066
3488
  async activate(owner, input, run, signal) {
3067
3489
  const state = this.stateFor(owner);
3490
+ if (state.dreamed === true) throw new Error(DREAM_ASKED);
3068
3491
  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
3492
  if (state.phase !== "idle" && state.phase !== "between") throw new Error(explainPhase(state, "activate_characters"));
3070
3493
  if (judgeDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3071
3494
  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"));
3495
+ if (this.previewHeld(state)) throw new Error(explainPhase(state, "activate_characters"));
3073
3496
  if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
3074
3497
  const store = this.storeOf(owner);
3075
3498
  const limit = store.settings().maxRounds;
@@ -3078,11 +3501,25 @@ var TurnEngine = class {
3078
3501
  if (situation === "") throw new Error("describe the situation: the characters are told nothing else");
3079
3502
  const cast = store.cast();
3080
3503
  const most = store.settings().maxCharacters;
3081
- const keys = this.boundaries().planner.plan({
3504
+ const planned = this.boundaries().planner.plan({
3082
3505
  cast,
3083
3506
  ...input.characters === void 0 ? {} : { requested: input.characters }
3084
3507
  });
3085
- if (keys.length === 0) throw new Error("there is no character to activate");
3508
+ const sleeping = planned.flatMap((key) => {
3509
+ const member = cast.find((candidate) => candidate.key === key);
3510
+ const asleep = member === void 0 || state.dreaming === key ? void 0 : store.asleep(owner.turn, member.character.id);
3511
+ return asleep === void 0 ? [] : [{
3512
+ key,
3513
+ name: member.character.name,
3514
+ until: asleep.until
3515
+ }];
3516
+ });
3517
+ const woken = sleeping.filter((entry) => input.wakes?.includes(entry.key) === true);
3518
+ const sleepers = sleeping.filter((entry) => !woken.includes(entry));
3519
+ 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`);
3520
+ const keys = planned.filter((key) => !sleepers.some((entry) => entry.key === key));
3521
+ 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");
3522
+ if (woken.length > 0) state.woken = /* @__PURE__ */ new Set([...state.woken ?? [], ...woken.map((entry) => entry.key)]);
3086
3523
  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
3524
  const signature = `${[...keys].sort((a, b) => a.localeCompare(b)).join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
3088
3525
  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 +3552,11 @@ var TurnEngine = class {
3115
3552
  async resolve(owner, outcomes, run, signal, elapsedSeconds) {
3116
3553
  const state = this.stateFor(owner);
3117
3554
  const store = this.storeOf(owner);
3555
+ if (state.dreamed === true) throw new Error(DREAM_ASKED);
3118
3556
  outcomes = mendRolls(outcomes, store, state);
3119
3557
  if (state.ooc !== void 0) return { done: this.decree(owner, state, outcomes, elapsedSeconds) };
3120
3558
  if (state.phase === "idle" || state.phase === "between") {
3121
- if (judgeDue(state) || previewDue(state)) throw new Error(explainPhase(state, "resolve_round"));
3559
+ if (judgeDue(state) || this.previewHeld(state)) throw new Error(explainPhase(state, "resolve_round"));
3122
3560
  if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
3123
3561
  const player = store.cast().find((member) => member.character.control === "player");
3124
3562
  if (player !== void 0 && outcomes.length === 1 && outcomes[0]?.character === player.key) return { done: this.resolvePlayer(owner, state, outcomes[0], elapsedSeconds) };
@@ -3187,6 +3625,14 @@ var TurnEngine = class {
3187
3625
  };
3188
3626
  return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
3189
3627
  }
3628
+ /** 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. */
3629
+ previewHeld(state) {
3630
+ if (!previewDue(state)) return false;
3631
+ state.previewRefusals += 1;
3632
+ if (state.previewRefusals <= MAX_PREVIEW_REFUSALS) return true;
3633
+ state.previewWanted = false;
3634
+ return false;
3635
+ }
3190
3636
  /** The turn settles a lone attempt in one step: nobody is asked to act, so there is no scene to preview. */
3191
3637
  withoutPreview(owner) {
3192
3638
  this.stateFor(owner).previewWanted = false;
@@ -3297,11 +3743,13 @@ var TurnEngine = class {
3297
3743
  */
3298
3744
  async narrate(owner, segments, run, addressed = []) {
3299
3745
  const state = this.stateFor(owner);
3746
+ if (state.phase === "idle") this.previewHeld(state);
3300
3747
  if (state.phase !== "between") throw new Error(explainPhase(state, "narrate"));
3301
3748
  const pending = new Set(this.storeOf(owner).pendingBeats().map((beat) => beat.id));
3302
3749
  const unknown = addressed.filter((id) => !pending.has(id));
3303
3750
  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
3751
  state.addressed = [...new Set(addressed)];
3752
+ 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
3753
  if (state.ooc !== void 0) {
3306
3754
  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
3755
  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 +3785,9 @@ var TurnEngine = class {
3337
3785
  * 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
3786
  */
3339
3787
  async expand(owner, input, signal) {
3340
- return await expandWorld(this.boundaries(), this.storeOf(owner), this.stateFor(owner), owner, input, signal);
3788
+ const state = this.stateFor(owner);
3789
+ 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`);
3790
+ return await expandWorld(this.boundaries(), this.storeOf(owner), state, owner, input, signal);
3341
3791
  }
3342
3792
  /** 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
3793
  introduce(owner, input) {
@@ -3534,6 +3984,17 @@ var TurnEngine = class {
3534
3984
  this.states.get(chat)?.cancel.abort();
3535
3985
  this.reflectionCancels.get(chat)?.abort();
3536
3986
  }
3987
+ /** The same for every chat the engine has seen; used when the plugin unloads. */
3988
+ stopAll() {
3989
+ for (const chat of /* @__PURE__ */ new Set([
3990
+ ...this.states.keys(),
3991
+ ...this.working.keys(),
3992
+ ...this.reflectionCancels.keys()
3993
+ ])) this.stop(chat);
3994
+ }
3995
+ async quiesceAll() {
3996
+ await Promise.all([.../* @__PURE__ */ new Set([...this.working.keys(), ...this.chains.keys()])].map((chat) => this.quiesce(chat)));
3997
+ }
3537
3998
  /** Resolves when nothing of the chat writes to its story any more: the records, what was made up being fitted in, the characters away, the suggestions. */
3538
3999
  async quiesce(chat, options = {}) {
3539
4000
  for (;;) {
@@ -3551,13 +4012,19 @@ var TurnEngine = class {
3551
4012
  this.chains.delete(chat);
3552
4013
  this.delivered.delete(chat);
3553
4014
  this.runs.delete(chat);
4015
+ this.failedRuns.delete(chat);
3554
4016
  this.working.delete(chat);
3555
4017
  for (const key of this.objections.keys()) if (key.startsWith(`${chat}#`)) this.objections.delete(key);
3556
4018
  }
3557
4019
  stateFor({ chat, turn }) {
3558
4020
  const known = this.states.get(chat);
3559
4021
  if (known?.turn === turn) return known;
3560
- const fresh = {
4022
+ const fresh = this.blankState(chat, turn);
4023
+ this.states.set(chat, fresh);
4024
+ return fresh;
4025
+ }
4026
+ blankState(chat, turn) {
4027
+ return {
3561
4028
  turn,
3562
4029
  phase: "idle",
3563
4030
  cast: [],
@@ -3573,6 +4040,7 @@ var TurnEngine = class {
3573
4040
  reported: /* @__PURE__ */ new Set(),
3574
4041
  refused: 0,
3575
4042
  previewed: false,
4043
+ previewRefusals: 0,
3576
4044
  previewWanted: this.stores(chat)?.settings().preview.enabled ?? false,
3577
4045
  focus: [],
3578
4046
  requested: false,
@@ -3582,8 +4050,16 @@ var TurnEngine = class {
3582
4050
  cues: /* @__PURE__ */ new Map(),
3583
4051
  addressed: []
3584
4052
  };
3585
- this.states.set(chat, fresh);
3586
- return fresh;
4053
+ }
4054
+ /**
4055
+ * 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
4056
+ * 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.
4057
+ */
4058
+ async askAlone(owner, key, situation, run, signal) {
4059
+ const store = this.storeOf(owner);
4060
+ const state = this.blankState(owner.chat, owner.turn);
4061
+ state.situation = situation;
4062
+ return (await this.ask(owner, 1, [key], store.cast(), state, run, signal, true)).reports[0];
3587
4063
  }
3588
4064
  storeOf(owner) {
3589
4065
  const store = this.stores(owner.chat);
@@ -3591,7 +4067,13 @@ var TurnEngine = class {
3591
4067
  return store;
3592
4068
  }
3593
4069
  ask(owner, number, keys, cast, state, run, signal, away = false) {
3594
- return askCharacters({
4070
+ const done = this.observe?.(owner.chat, {
4071
+ turn: owner.turn,
4072
+ attempt: number,
4073
+ characters: keys,
4074
+ away
4075
+ });
4076
+ const asked = askCharacters({
3595
4077
  boundaries: this.boundaries(),
3596
4078
  store: this.stores(owner.chat),
3597
4079
  storeOf: (o) => this.storeOf(o),
@@ -3599,6 +4081,14 @@ var TurnEngine = class {
3599
4081
  this.problem(message);
3600
4082
  }
3601
4083
  }, owner, number, keys, cast, state, run, signal, away);
4084
+ if (done === void 0) return asked;
4085
+ return asked.then((attempt) => {
4086
+ done(attempt);
4087
+ return attempt;
4088
+ }, (error) => {
4089
+ done(error instanceof Error ? error : new Error(String(error)));
4090
+ throw error;
4091
+ });
3602
4092
  }
3603
4093
  /**
3604
4094
  * The game master asks for what happened to be written into the story's lasting records. The memory
@@ -3726,8 +4216,24 @@ var TurnEngine = class {
3726
4216
  state.refused += 1;
3727
4217
  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
4218
  }
4219
+ /**
4220
+ * 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
4221
+ * 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.
4222
+ */
4223
+ checkArrival(owner, state, silent) {
4224
+ const goesTo = state.judgement?.goesTo;
4225
+ if (goesTo === void 0 || silent || state.arrivalChecked === true || state.ooc !== void 0) return;
4226
+ const store = this.storeOf(owner);
4227
+ const player = store.cast().find((member) => member.character.control === "player");
4228
+ if (player?.place === void 0) return;
4229
+ const found = whereabouts(store.story.locations.list(), player.place.location, goesTo);
4230
+ if (found.kind !== "elsewhere") return;
4231
+ state.arrivalChecked = true;
4232
+ 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`);
4233
+ }
3729
4234
  async deliver(owner, state, segments, silent, run) {
3730
4235
  let output = checkedOutput(this.boundaries().narrationChecker, this.storeOf(owner).settings().prompts.language, state, segments, silent);
4236
+ this.checkArrival(owner, state, silent);
3731
4237
  await this.gate(owner, state, output, silent);
3732
4238
  if (state.ooc?.ruling !== void 0) output = {
3733
4239
  ...output,
@@ -3802,6 +4308,10 @@ var ImageJobs = class {
3802
4308
  this.active.get(id)?.controller.abort();
3803
4309
  this.active.delete(id);
3804
4310
  }
4311
+ cancelAll() {
4312
+ for (const job of this.active.values()) job.controller.abort();
4313
+ this.active.clear();
4314
+ }
3805
4315
  /**
3806
4316
  * @param priority - `foreground` when the player asked for the picture, `background` when it is made on its own after a turn and may wait behind the next one.
3807
4317
  * @param automatic - the picture was not asked for: the library is looked at first, and the pictures the person brought are described before that.
@@ -4019,7 +4529,7 @@ function pictureReuse(deps) {
4019
4529
  key: `picture${index}`,
4020
4530
  instructions: job.store.text("roleplay/decide-reuse", { description: image.description.trim() })
4021
4531
  }));
4022
- const { found, report } = await askExtra(deps.decisions?.(), { moment: job.moment.slice(0, MOMENT_CHARS) }, asks, settings.decisions.gateThreshold, signal);
4532
+ const { found, report } = await askExtra(deps.decisions?.(), { moment: job.moment.slice(0, MOMENT_CHARS) }, asks, settings.decisions.reuseThreshold, signal);
4023
4533
  noteExtra("reuse", job.chat, job.store, report, seen, deps.problem);
4024
4534
  const first = found[0];
4025
4535
  return first === void 0 ? void 0 : matches[Number(first.slice(7))].image.path;
@@ -4043,6 +4553,7 @@ const inject = [
4043
4553
  "agents"
4044
4554
  ];
4045
4555
  function apply(ctx) {
4556
+ silenceHarnessDevContext(ctx);
4046
4557
  const boundaries = () => ctx.roleplayOrchestration.boundaries;
4047
4558
  const problem = (message) => {
4048
4559
  ctx.logger.warn(`roleplay: ${message}`);
@@ -4083,6 +4594,7 @@ function apply(ctx) {
4083
4594
  ctx.effect(() => ctx.roleplayOrchestration.replace({ outputGate: outputGates({
4084
4595
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
4085
4596
  decisions,
4597
+ earlier: (chat, count) => timelines.narrationBefore(chat, count),
4086
4598
  problem
4087
4599
  }) }), "roleplay: output gates");
4088
4600
  ctx.effect(() => ctx.roleplayOrchestration.replace({ ruleCheck: ruleChecks({
@@ -4099,6 +4611,10 @@ function apply(ctx) {
4099
4611
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
4100
4612
  external: (parent) => ctx.get("roleplayAuthoringTools")?.given(parent.ctx.tools, "worldAuthor") ?? []
4101
4613
  }) }), "roleplay: world author");
4614
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ errandKeeper: errandChecks({
4615
+ decisions,
4616
+ problem
4617
+ }) }), "roleplay: errands");
4102
4618
  ctx.effect(() => ctx.roleplayOrchestration.replace({ variableTracker: variableTracker({
4103
4619
  agentOf: (chat) => ctx.agents.get(SessionId(chat)),
4104
4620
  decisions,
@@ -4137,7 +4653,7 @@ function apply(ctx) {
4137
4653
  "list_checks"
4138
4654
  ].filter((tool) => toolEnabled(chat.settings.tools, "gameMaster", tool));
4139
4655
  if (on.length === 0) return "";
4140
- const checks = on.includes("roll_check") ? describeChecks(store.story.dice.checks(), translator(languageOf(language))) : "";
4656
+ const checks = on.includes("roll_check") ? describeChecks(store.story.dice.checks(), translator(languageOf$1(language))) : "";
4141
4657
  return ctx.roleplayPrompts.text("roleplay/dice", language, {
4142
4658
  tools: on.join(", "),
4143
4659
  checks
@@ -4146,7 +4662,7 @@ function apply(ctx) {
4146
4662
  /** 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
4663
  const standingSection = (text, language) => {
4148
4664
  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}`;
4665
+ return `${translator(languageOf$1(language))("The standing rules of this world. Apply them on every turn:")}\n\n${text}`;
4150
4666
  };
4151
4667
  for (const [name, order, id] of [[
4152
4668
  PERSONA_SECTION,
@@ -4178,7 +4694,7 @@ function apply(ctx) {
4178
4694
  interpolate: false,
4179
4695
  text: (context) => {
4180
4696
  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")));
4697
+ 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
4698
  }
4183
4699
  });
4184
4700
  ctx.systemPrompt.context({
@@ -4188,6 +4704,7 @@ function apply(ctx) {
4188
4704
  text: ""
4189
4705
  });
4190
4706
  const rolls = new RollReplay((chat) => stores(chat)?.settings().rewind.rolls ?? "reroll");
4707
+ const turnTraces = new TurnTraces(() => tracerOf(ctx));
4191
4708
  const toolDeps = {
4192
4709
  engine,
4193
4710
  boundaries,
@@ -4195,6 +4712,7 @@ function apply(ctx) {
4195
4712
  turnOf: currentTurn,
4196
4713
  roller: (chat) => rolls.roller(chat),
4197
4714
  delivered: (chat, output) => {
4715
+ turnTraces.output(chat, output.segments.map((segment) => segment.type === "utterance" ? `${segment.name}: ${segment.text}` : segment.text).join("\n\n"));
4198
4716
  const node = timelines.delivered(chat, output);
4199
4717
  if (node !== void 0) images.afterDelivery(chat, node, output);
4200
4718
  return node;
@@ -4214,6 +4732,43 @@ function apply(ctx) {
4214
4732
  ctx.roleplayOrchestration.playing = () => false;
4215
4733
  };
4216
4734
  }, "roleplay: reflection control");
4735
+ ctx.effect(() => {
4736
+ ctx.roleplayOrchestration.autonomy = async (chat, signal) => {
4737
+ const started = Date.now();
4738
+ const run = await tickAutonomy({
4739
+ engine,
4740
+ stores,
4741
+ boundaries,
4742
+ agentOf: (id) => ctx.agents.get(SessionId(id)),
4743
+ wall: Date.now,
4744
+ problem,
4745
+ decisions
4746
+ }, chat, signal);
4747
+ stores(chat)?.autonomy?.looked?.(run.outcome, Date.now());
4748
+ const tracer = tracerOf(ctx);
4749
+ if (tracer !== void 0 && (run.moved > 0 || run.outcome === "wrote" || run.outcome === "declined")) tracer.start({
4750
+ name: "autonomy look",
4751
+ kind: "span",
4752
+ metadata: {
4753
+ outcome: run.outcome,
4754
+ moved: run.moved,
4755
+ seconds: (Date.now() - started) / 1e3
4756
+ },
4757
+ trace: {
4758
+ name: "autonomy look",
4759
+ sessionId: sessionOfChat(chat),
4760
+ tags: ["roleplay", "autonomy"]
4761
+ }
4762
+ }).end({ output: run });
4763
+ return run;
4764
+ };
4765
+ return () => {
4766
+ ctx.roleplayOrchestration.autonomy = () => Promise.resolve({
4767
+ outcome: "off",
4768
+ moved: 0
4769
+ });
4770
+ };
4771
+ }, "roleplay: autonomy");
4217
4772
  ctx.effect(() => {
4218
4773
  ctx.roleplayOrchestration.settle = (chat) => engine.idle(chat);
4219
4774
  return () => {
@@ -4262,9 +4817,12 @@ function apply(ctx) {
4262
4817
  engine.forget(chat);
4263
4818
  };
4264
4819
  ctx.roleplayOrchestration.quiesce = (chat) => engine.quiesce(chat);
4265
- return () => {
4820
+ return async () => {
4266
4821
  ctx.roleplayOrchestration.halt = () => Promise.resolve();
4267
4822
  ctx.roleplayOrchestration.quiesce = () => Promise.resolve();
4823
+ images.cancelAll();
4824
+ engine.stopAll();
4825
+ await engine.quiesceAll();
4268
4826
  };
4269
4827
  }, "roleplay: halt");
4270
4828
  ctx.effect(() => {
@@ -4287,12 +4845,21 @@ function apply(ctx) {
4287
4845
  turn: currentTurn(agent)
4288
4846
  };
4289
4847
  };
4848
+ registerFoldersJail(ctx, {
4849
+ roots: async (session) => await storyRoots(ctx.roleplayRoot.path, sessionFolder(sessionsDir(), session)),
4850
+ workspace: () => workspaceOf(ctx.roleplayRoot.path)
4851
+ });
4290
4852
  installHooks(ctx, {
4853
+ traces: turnTraces,
4291
4854
  engine,
4292
4855
  boundaries,
4293
4856
  stores,
4294
4857
  timelines,
4295
4858
  rolls,
4859
+ folders: async (chat) => {
4860
+ const session = roleplaySessionOf(chat);
4861
+ return session === void 0 ? void 0 : await storyRoots(ctx.roleplayRoot.path, sessionFolder(sessionsDir(), session));
4862
+ },
4296
4863
  previewTool,
4297
4864
  optionalTools: [...createDiceTools(diceLink, { rollerFor: (chat) => rolls.roller(chat) }), createCheckNarrateTool(toolDeps)]
4298
4865
  });