@dsh-agentic-roleplay/core 0.2.1 → 0.3.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 (48) hide show
  1. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  2. package/lib/authoring.js +193 -227
  3. package/lib/client.js +2710 -1322
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +2 -3
  6. package/lib/deliver-BDW5WZvc.js +2262 -0
  7. package/lib/{documents-Bu5uYRZB.js → documents-DtlY2IRt.js} +958 -10
  8. package/lib/{gallery-DUeBMHQX.js → gallery-DACG5eh2.js} +2 -2
  9. package/lib/{generator-HPifO3Kk.js → generator-DGYcLMp7.js} +2 -2
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +419 -23
  12. package/lib/{narration-BRyHU0H2.js → narration-5ig7Dg28.js} +12 -2
  13. package/lib/orchestration.js +458 -342
  14. package/lib/{packs-ByP1J-zj.js → packs-CkRZDCsV.js} +51 -5
  15. package/lib/{presenter-agent-G43ODV8I.js → presenter-agent-PK9JYExk.js} +4 -4
  16. package/package.json +5 -4
  17. package/packs/scene/map.html +12 -0
  18. package/packs/scene/map.js +55 -0
  19. package/packs/scene/pack.json +11 -0
  20. package/packs/scene/strip.html +11 -0
  21. package/packs/scene/strip.js +26 -0
  22. package/packs/scene/style.css +16 -0
  23. package/prompts/en/roleplay/character-decide.md +1 -1
  24. package/prompts/en/roleplay/character-rules.md +1 -1
  25. package/prompts/en/roleplay/chronicler.md +1 -1
  26. package/prompts/en/roleplay/game-master.md +1 -1
  27. package/prompts/en/roleplay/reflection.md +9 -0
  28. package/prompts/en/roleplay/style.md +1 -1
  29. package/prompts/en/roleplay/suggester.md +1 -1
  30. package/prompts/en/translate/document.md +6 -0
  31. package/prompts/en/translate/glossary.md +5 -0
  32. package/prompts/en/translate/notice.md +2 -0
  33. package/prompts/en/world/procedure.md +1 -1
  34. package/prompts/en/world/welcome.md +1 -1
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-rules.md +1 -1
  37. package/prompts/zh/roleplay/chronicler.md +1 -1
  38. package/prompts/zh/roleplay/game-master.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/roleplay/style.md +1 -1
  41. package/prompts/zh/roleplay/suggester.md +1 -1
  42. package/prompts/zh/translate/document.md +6 -0
  43. package/prompts/zh/translate/glossary.md +5 -0
  44. package/prompts/zh/translate/notice.md +2 -0
  45. package/prompts/zh/world/procedure.md +1 -1
  46. package/prompts/zh/world/welcome.md +1 -1
  47. package/lib/access-C1nFQiyT.js +0 -12
  48. package/lib/activity-t7OBgHlc.js +0 -1386
@@ -1,12 +1,11 @@
1
- import { n as roleplaySessionOf, t as chatSessionId } from "./chat-AKrVcWIC.js";
2
- import { F as shippedText, U as INTENT_STATUSES, _ as API_PREFIX, b as parsePlotsFile } from "./packs-ByP1J-zj.js";
3
- import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-BRyHU0H2.js";
1
+ import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { B as shippedText, S as wrongLanguage, T as parsePlotsFile, W as ReflectionRefusedError, Y as INTENT_STATUSES, _ as API_PREFIX } from "./packs-CkRZDCsV.js";
3
+ import { B as skipTime, D as observeSurroundings, E as observeAsPlayer, F as beginTurn, G as RESULTS, H as referent, I as describeTime, J as languageOf, K as answerEstimate, L as describeWhen, N as sameWords, P as ClockError, R as endRound, S as clearNotes, T as readNotes, U as AWAY_ACTION_SCHEMA, V as zoneOf, W as CHARACTER_ACTION_SCHEMA, Y as translator, _ as plotAuthorNeeded, b as updatePlotProgress, c as dueReflection, f as whereabouts, g as pacingAdvice, h as describePacingAdvice, i as keepRunDetail, k as Timelines, l as memoryReflector, m as addSessionPlot, q as parseCharacterAction, r as forgetRunDetails, s as recordActivity, t as deliverNow, u as recordFailure, w as putNote, x as addToNote, z as readTime } from "./deliver-BDW5WZvc.js";
4
+ import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-5ig7Dg28.js";
4
5
  import "./src-CWTNeL6Y.js";
5
- import { A as runChild, D as childSampling, E as childModel, T as uniqueKey, j as estimateAnswer, k as childTrace, o as addToLibrary, w as slug } from "./generator-HPifO3Kk.js";
6
- import { A as readTime, D as describeTime, E as beginTurn, F as CHARACTER_ACTION_SCHEMA, I as RESULTS, L as answerEstimate, M as zoneOf, N as referent, O as describeWhen, P as AWAY_ACTION_SCHEMA, R as parseCharacterAction, T as ClockError, _ as putNote, a as recordActivity, b as Timelines, c as describePacingAdvice, h as clearNotes, j as skipTime, k as endRound, l as pacingAdvice, m as addToNote, n as keepRunDetail, p as updatePlotProgress, s as addSessionPlot, t as forgetRunDetails, u as plotAuthorNeeded, v as readNotes, w as sameWords } from "./activity-t7OBgHlc.js";
7
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DUeBMHQX.js";
8
- import { t as promptFor } from "./access-C1nFQiyT.js";
9
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-G43ODV8I.js";
6
+ import { A as runChild, D as childSampling, E as childModel, M as tokensOf, T as uniqueKey, j as estimateAnswer, k as childTrace, o as addToLibrary, w as slug } from "./generator-DGYcLMp7.js";
7
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DACG5eh2.js";
8
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PK9JYExk.js";
10
9
  import { join } from "node:path";
11
10
  import { existsSync } from "node:fs";
12
11
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -137,6 +136,16 @@ function keeperTools(job, memory, progress) {
137
136
  execute: async (args, exec) => {
138
137
  const outside = (parseRecordsEdit(args).events ?? []).filter((event) => !job.rounds.some((round) => round.turn === event.turn && round.round === event.round));
139
138
  if (outside.length > 0) throw new InvalidEditError(outside.map((event) => `an event has turn ${event.turn}, round ${event.round}, which is not one of the rounds given: ${job.rounds.map(label).join("; ")}`));
139
+ const edit = parseRecordsEdit(args);
140
+ const wording = wrongLanguage(job.store.settings().prompts.language, {
141
+ events: [...(edit.events ?? []).map((event) => event.text), ...(edit.eventEdits ?? []).map((event) => event.text)].join(" "),
142
+ perceptions: [
143
+ ...(edit.events ?? []).flatMap((event) => (event.perceivedBy ?? []).map((seen) => seen.content)),
144
+ ...(edit.perceptionEdits ?? []).map((seen) => seen.content),
145
+ ...(edit.perceptionsAdded ?? []).map((seen) => seen.content)
146
+ ].join(" ")
147
+ });
148
+ if (wording !== void 0) throw new InvalidEditError([wording]);
140
149
  const result = await tool.execute(args, exec);
141
150
  progress.edits += 1;
142
151
  progress.unchecked = true;
@@ -161,6 +170,9 @@ function keeperTools(job, memory, progress) {
161
170
  return tool;
162
171
  });
163
172
  }
173
+ /** What one request of the keeper may carry: the events and what each witness took in, for every round it was given, and the shape of the call. */
174
+ const KEEPER_CHARACTERS_PER_ROUND = 4e3;
175
+ const keeperEstimate = (rounds, language) => tokensOf(rounds * KEEPER_CHARACTERS_PER_ROUND, language) + 192;
164
176
  /**
165
177
  * Writes rounds into the story's records with a child agent of the game master that has the
166
178
  * record tools to itself (the game master and the characters never see them). It writes with
@@ -187,7 +199,7 @@ function recordKeeper(deps) {
187
199
  parent,
188
200
  signal,
189
201
  reasoningEffort: job.store.settings().reasoning.children,
190
- sampling: childSampling(job.store.settings(), "records"),
202
+ sampling: childSampling(job.store.settings(), "records", keeperEstimate(job.rounds.length, job.store.settings().prompts.language)),
191
203
  ...childModel(job.store.settings(), "records"),
192
204
  trace: childTrace(job.store, "records", "record keeper"),
193
205
  persona: promptFor(parent, "roleplay/record-keeper", job.store.settings().prompts.language),
@@ -359,7 +371,7 @@ function triggerJudge(deps) {
359
371
  parent,
360
372
  signal,
361
373
  reasoningEffort: store.settings().reasoning.children,
362
- sampling: childSampling(store.settings(), "records"),
374
+ sampling: childSampling(store.settings(), "records", statements.length * 2 * 8 + 8),
363
375
  ...childModel(store.settings(), "records"),
364
376
  trace: childTrace(store, "records", "trigger judge"),
365
377
  persona: promptFor(parent, "roleplay/trigger-judge", store.settings().prompts.language),
@@ -392,6 +404,16 @@ const DAY_MS = 864e5;
392
404
  const STRATEGY_ROUND = 200;
393
405
  const MAX_ACTIVE_GOALS = 8;
394
406
  const MAX_TEXT = 400;
407
+ /** What a decision may hold: the summary, both states, a new goal with its plan, and the status of each active goal. */
408
+ const DECISION_LIMITS = [
409
+ MAX_TEXT,
410
+ MAX_TEXT,
411
+ MAX_TEXT,
412
+ 120,
413
+ MAX_TEXT,
414
+ ...Array.from({ length: 6 }, () => 200),
415
+ ...Array.from({ length: MAX_ACTIVE_GOALS }, () => 10)
416
+ ];
395
417
  const keyOf$1 = (faction) => faction.sourceId ?? String(faction.id);
396
418
  function lastActed(session) {
397
419
  const stored = session.metadata.getValue(LAST_KEY);
@@ -564,7 +586,7 @@ function factionStrategist(deps) {
564
586
  parent,
565
587
  signal,
566
588
  reasoningEffort: store.settings().reasoning.children,
567
- sampling: childSampling(store.settings(), "authoring"),
589
+ sampling: childSampling(store.settings(), "authoring", estimateAnswer(DECISION_LIMITS, store.settings().prompts.language)),
568
590
  ...childModel(store.settings(), "authoring"),
569
591
  trace: childTrace(store, "authoring", `faction ${faction.name}`),
570
592
  persona: promptFor(parent, "roleplay/faction-strategist", store.settings().prompts.language),
@@ -583,6 +605,13 @@ function factionStrategist(deps) {
583
605
  }
584
606
  //#endregion
585
607
  //#region src/host/authoring/author-agent.ts
608
+ /** A made-up thing in one edit: its name, description and the handful of fields a character, place or item carries. */
609
+ const THING_TEXTS = 14;
610
+ const THING_TEXT_CHARS = 300;
611
+ /** What consolidating one waiting item writes: a way or a relationship with its descriptions. */
612
+ const FIT_TEXTS = 6;
613
+ const FIT_TEXT_CHARS = 200;
614
+ const editEstimate = (things, texts, chars, language) => estimateAnswer(Array.from({ length: Math.max(1, things) * texts }, () => chars), language);
586
615
  function authorTools(job, work, mode, limits) {
587
616
  const link = {
588
617
  session: job.store.story,
@@ -826,7 +855,7 @@ function worldAuthor(deps) {
826
855
  const work = { created: [] };
827
856
  const result = await runChild({
828
857
  reasoningEffort: job.store.settings().reasoning.children,
829
- sampling: childSampling(job.store.settings(), "authoring"),
858
+ sampling: childSampling(job.store.settings(), "authoring", editEstimate(authoring.perTurn, THING_TEXTS, THING_TEXT_CHARS, job.store.settings().prompts.language)),
830
859
  ...childModel(job.store.settings(), "authoring"),
831
860
  trace: childTrace(job.store, "authoring", "world author"),
832
861
  parent,
@@ -869,7 +898,7 @@ function worldAuthor(deps) {
869
898
  const work = { created: [] };
870
899
  const result = await runChild({
871
900
  reasoningEffort: job.store.settings().reasoning.children,
872
- sampling: childSampling(job.store.settings(), "authoring"),
901
+ sampling: childSampling(job.store.settings(), "authoring", editEstimate(pending.length, FIT_TEXTS, FIT_TEXT_CHARS, job.store.settings().prompts.language)),
873
902
  ...childModel(job.store.settings(), "authoring"),
874
903
  trace: childTrace(job.store, "authoring", "world consolidation"),
875
904
  parent,
@@ -913,20 +942,23 @@ function fireTriggers(session, input) {
913
942
  for (const failure of run.failed) problem(`the trigger "${failure.trigger.key}" could not fire and is given up: ${failure.problem}`);
914
943
  const names = new Map(session.characters.list().map((character) => [character.id, character.name]));
915
944
  const fresh = session.triggers.notes({ status: "pending" }).filter((note) => note.id > before);
945
+ const told = new Map(deliverNow(session, fresh, {
946
+ now,
947
+ zone
948
+ }).map((entry) => [entry.id, entry.text]));
916
949
  return { fired: run.fired.map((fired) => ({
917
950
  name: fired.trigger.name,
918
951
  events: fired.events,
919
- cues: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "cue").map((note) => ({
952
+ cues: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "cue" && told.has(note.id)).map((note) => ({
920
953
  names: note.characterIds.flatMap((id) => names.get(id) ?? []),
921
- text: note.text
954
+ text: told.get(note.id)
922
955
  })),
923
- beats: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "beat").map((note) => ({
956
+ beats: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "beat" && told.has(note.id)).map((note) => ({
924
957
  id: note.id,
925
- text: note.text
958
+ text: told.get(note.id)
926
959
  }))
927
960
  })) };
928
961
  }
929
- /** The beats still to weave in, the cues of a character, and what is done with them. */
930
962
  /** When something is to happen, as it is told: the date and how far off it is. */
931
963
  function whenText(at, clock) {
932
964
  if (at === void 0) return void 0;
@@ -940,6 +972,7 @@ function whoKnows(session, announcement) {
940
972
  }
941
973
  /** At most this many announcements are told to one character at once: soonest first. */
942
974
  const MAX_UPCOMING_FOR_CHARACTER = 3;
975
+ /** The beats still to weave in, the cues of a character, and what is done with them. Each is written from the story as it stands when it is told, and one that no longer applies is withdrawn. */
943
976
  function noteStore(session, settings, clock) {
944
977
  return {
945
978
  upcoming: (turn) => {
@@ -963,13 +996,10 @@ function noteStore(session, settings, clock) {
963
996
  };
964
997
  });
965
998
  },
966
- pendingBeats: () => session.triggers.notes({
999
+ pendingBeats: () => deliverNow(session, session.triggers.notes({
967
1000
  status: "pending",
968
1001
  kind: "beat"
969
- }).map((note) => ({
970
- id: note.id,
971
- text: note.text
972
- })),
1002
+ }), clock(session.metadata.get().turns + 1)),
973
1003
  resolveBeats: (ids) => {
974
1004
  const pending = new Set(session.triggers.notes({
975
1005
  status: "pending",
@@ -981,13 +1011,10 @@ function noteStore(session, settings, clock) {
981
1011
  for (const id of ids) session.triggers.resolveNote(id, "done");
982
1012
  });
983
1013
  },
984
- cuesFor: (characterId) => session.triggers.notes({
1014
+ cuesFor: (characterId) => deliverNow(session, session.triggers.notes({
985
1015
  status: "pending",
986
1016
  kind: "cue"
987
- }).filter((note) => note.characterIds.includes(characterId)).map((note) => ({
988
- id: note.id,
989
- text: note.text
990
- })),
1017
+ }).filter((note) => note.characterIds.includes(characterId)), clock(session.metadata.get().turns + 1)),
991
1018
  doneCues: (ids) => {
992
1019
  session.transaction(() => {
993
1020
  for (const id of ids) session.triggers.resolveNote(id, "done");
@@ -1003,35 +1030,6 @@ function noteStore(session, settings, clock) {
1003
1030
  };
1004
1031
  }
1005
1032
  //#endregion
1006
- //#region src/host/orchestration/observation.ts
1007
- /** What a character takes in where it stands and of what it carries: the place, the ways out and what they lead to, what lies in the open, what it holds. */
1008
- function observeSurroundings(session, characterId, turn) {
1009
- const placement = session.placements.get("character", characterId);
1010
- if (placement !== void 0) {
1011
- session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1012
- for (const exit of session.locations.exitsFrom(placement.locationId)) {
1013
- session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1014
- session.knowledge.learn(characterId, "location", exit.toId, turn);
1015
- }
1016
- for (const { item } of session.items.contents({
1017
- kind: "location",
1018
- id: placement.locationId
1019
- })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1020
- }
1021
- for (const { item } of session.items.contents({
1022
- kind: "character",
1023
- id: characterId
1024
- })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1025
- }
1026
- /**
1027
- * The player's character is never asked to act, so nothing else shows it its surroundings: it takes them in when a turn begins, which is
1028
- * how it comes to know the way back from where it went.
1029
- */
1030
- function observeAsPlayer(session, turn) {
1031
- const player = session.characters.list().find((character) => character.control === "player");
1032
- if (player !== void 0) observeSurroundings(session, player.id, turn);
1033
- }
1034
- //#endregion
1035
1033
  //#region src/host/clock/agenda.ts
1036
1034
  const CURSOR = "agenda.cursor";
1037
1035
  const ASKED = "agenda.asked";
@@ -1237,7 +1235,9 @@ function markHandled(session, keys) {
1237
1235
  * whose time has come with everyone to do with them away from the scene, and goals whose deadline has passed.
1238
1236
  * Oldest first.
1239
1237
  */
1240
- function dueOffScene(session, zone, now) {
1238
+ function dueOffScene(session, zone, now, language = "en") {
1239
+ const tr = translator(language);
1240
+ const when = (instant) => describeWhen(instant, now, zone, language);
1241
1241
  const handled = handledKeys(session);
1242
1242
  const characters = session.characters.list();
1243
1243
  const player = characters.find((character) => character.control === "player");
@@ -1260,7 +1260,19 @@ function dueOffScene(session, zone, now) {
1260
1260
  at: engagement.at,
1261
1261
  characters: everyone.map((id) => keyOf(agents.get(id))),
1262
1262
  ...place === void 0 ? {} : { place: place.sourceId ?? String(place.id) },
1263
- text: `You were to ${engagement.title}${place === void 0 ? "" : ` at ${place.name}`}, at ${describeWhen(engagement.at, now, zone)}${engagement.note === "" ? "" : ` (${engagement.note})`}. It is ${describeWhen(now, now, zone)} now${now > engagement.at + ENGAGEMENT_GRACE ? " and the time has passed" : ""}. It was with: ${everyone.map((id) => agents.get(id).name).join(", ")}. You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.`
1263
+ text: [
1264
+ `${place === void 0 ? tr("You were to {title}, at {when}", {
1265
+ title: engagement.title,
1266
+ when: when(engagement.at)
1267
+ }) : tr("You were to {title} at {place}, at {when}", {
1268
+ title: engagement.title,
1269
+ place: place.name,
1270
+ when: when(engagement.at)
1271
+ })}${engagement.note === "" ? "" : tr(" ({note})", { note: engagement.note })}${tr(".")}`,
1272
+ now > engagement.at + ENGAGEMENT_GRACE ? tr("It is {now} now and the time has passed.", { now: when(now) }) : tr("It is {now} now.", { now: when(now) }),
1273
+ tr("It was with: {who}.", { who: everyone.map((id) => agents.get(id).name).join(tr(", ")) }),
1274
+ tr("You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.")
1275
+ ].join(" ")
1264
1276
  });
1265
1277
  }
1266
1278
  for (const character of agents.values()) {
@@ -1279,7 +1291,11 @@ function dueOffScene(session, zone, now) {
1279
1291
  kind: "goal",
1280
1292
  at: deadline,
1281
1293
  characters: [keyOf(character)],
1282
- text: `The time you had for "${goal.name}" has passed (${describeWhen(deadline, now, zone)}; it is ${describeWhen(now, now, zone)} now)${goal.description === "" ? "" : `: ${goal.description}`} You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.`
1294
+ text: `${tr("The time you had for \"{goal}\" has passed ({when}; it is {now} now)", {
1295
+ goal: goal.name,
1296
+ when: when(deadline),
1297
+ now: when(now)
1298
+ })}${goal.description === "" ? "" : `${tr(": ")}${goal.description}`} ${tr("You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.")}`
1283
1299
  });
1284
1300
  }
1285
1301
  }
@@ -1584,7 +1600,7 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
1584
1600
  changeVariables: (turn, changes) => session.transaction(() => changes.map((spec) => changeVariable(session, spec, turn))),
1585
1601
  trackedFor: (characterId, presentIds) => trackedFor(session, characterId, presentIds),
1586
1602
  tracked: () => trackedLines(session),
1587
- dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now),
1603
+ dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now, languageOf(settings().prompts.language)),
1588
1604
  markHandled: (keys) => {
1589
1605
  markHandled(session, keys);
1590
1606
  },
@@ -1762,9 +1778,16 @@ function installHooks(ctx, deps) {
1762
1778
  store.clearNotes();
1763
1779
  store.lapseNotes(payload.turn);
1764
1780
  const { time, away, agenda } = store.beginTurn(payload.turn);
1765
- if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => `${move.name} went to ${move.to}.`));
1781
+ const tr = translator(languageOf(store.settings().prompts.language));
1782
+ if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => tr("{name} went to {place}.", {
1783
+ name: move.name,
1784
+ place: move.to
1785
+ })));
1766
1786
  const world = {
1767
- happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => `${cue.names.join(" and ")} noticed: ${cue.text}`)]),
1787
+ happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
1788
+ names: cue.names.join(tr(" and ")),
1789
+ text: cue.text
1790
+ }))]),
1768
1791
  beats: store.pendingBeats(),
1769
1792
  upcoming: store.upcoming(payload.turn)
1770
1793
  };
@@ -1785,6 +1808,7 @@ function installHooks(ctx, deps) {
1785
1808
  at: (locationId) => store.itemsAt(locationId, true),
1786
1809
  carried: (characterId) => store.carried(characterId)
1787
1810
  },
1811
+ language: store.settings().prompts.language,
1788
1812
  ...queryVector === void 0 ? {} : { queryVector }
1789
1813
  })];
1790
1814
  const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
@@ -1853,11 +1877,22 @@ function characterRunner(deps) {
1853
1877
  tools,
1854
1878
  maxCalls: deps.store.settings().memory.lookupCalls,
1855
1879
  result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
1856
- unenforced: ["thought"]
1880
+ unenforced: ["thought"],
1881
+ beforeSubmit: (value) => spokenIn(settings.prompts.language, value)
1857
1882
  });
1858
1883
  return parseCharacterAction(result);
1859
1884
  };
1860
1885
  }
1886
+ /** A character whose sheet is in another language than the chat's writes in the sheet's: the answer is refused until it is in the chat's. */
1887
+ function spokenIn(language, value) {
1888
+ const given = value;
1889
+ return wrongLanguage(language, {
1890
+ thought: given.thought,
1891
+ intent: given.intent,
1892
+ utterance: given.utterance,
1893
+ account: given.account
1894
+ });
1895
+ }
1861
1896
  /** What the character was reminded of and why, for the run's record, when the recall said why. */
1862
1897
  function recalledOf(request) {
1863
1898
  const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
@@ -2006,6 +2041,9 @@ const RESULT = {
2006
2041
  }
2007
2042
  }
2008
2043
  };
2044
+ /** A scaffold is about two dozen short texts: premise, hook, developments with their guidance, stakes and resolutions. */
2045
+ const PLOT_TEXTS = 24;
2046
+ const PLOT_TEXT_CHARS = 300;
2009
2047
  async function authorPlot(parent, store, turn, signal) {
2010
2048
  const cast = store.cast().map((member) => `${member.character.name} (${member.key}): ${member.character.summary}`).join("\n");
2011
2049
  const factions = store.story.factions.list().map((faction) => `${faction.name} (${faction.sourceId ?? faction.id}): ${faction.summary}`).join("\n");
@@ -2015,7 +2053,7 @@ async function authorPlot(parent, store, turn, signal) {
2015
2053
  const result = await runChild({
2016
2054
  parent,
2017
2055
  signal,
2018
- sampling: childSampling(store.settings(), "authoring"),
2056
+ sampling: childSampling(store.settings(), "authoring", estimateAnswer(Array.from({ length: PLOT_TEXTS }, () => PLOT_TEXT_CHARS), store.settings().prompts.language)),
2019
2057
  ...childModel(store.settings(), "authoring"),
2020
2058
  trace: childTrace(store, "authoring", "plot author"),
2021
2059
  persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
@@ -2959,6 +2997,7 @@ var AfterTurnJobs = class {
2959
2997
  consolidating = /* @__PURE__ */ new Set();
2960
2998
  strategizing = /* @__PURE__ */ new Set();
2961
2999
  judging = /* @__PURE__ */ new Set();
3000
+ reflecting = /* @__PURE__ */ new Set();
2962
3001
  constructor(deps) {
2963
3002
  this.deps = deps;
2964
3003
  }
@@ -2966,6 +3005,42 @@ var AfterTurnJobs = class {
2966
3005
  this.consolidate(owner, cancel);
2967
3006
  this.strategize(owner, cancel);
2968
3007
  this.judge(owner, cancel);
3008
+ const reason = this.reflectionDue(owner);
3009
+ if (reason !== void 0) this.reflect(owner, reason, cancel);
3010
+ }
3011
+ /** Whether a reflection is running for the chat. */
3012
+ isReflecting(chat) {
3013
+ return this.reflecting.has(chat);
3014
+ }
3015
+ /** Starts a reflection the player asked for, without waiting for it. @throws {ReflectionRefusedError} when one is already running. */
3016
+ reflectNow(owner, cancel) {
3017
+ if (this.deps.stores(owner.chat) === void 0) throw new Error(`no story for chat ${owner.chat}`);
3018
+ if (this.reflecting.has(owner.chat)) throw new ReflectionRefusedError("a reflection is already running");
3019
+ this.reflect(owner, "manual", cancel);
3020
+ }
3021
+ reflectionDue(owner) {
3022
+ const store = this.deps.stores(owner.chat);
3023
+ return store === void 0 || this.reflecting.has(owner.chat) ? void 0 : dueReflection(store, owner.turn);
3024
+ }
3025
+ /** The characters sort what they have taken in into what they believe. The one failure that matters to the player, a pass they asked for, is kept for the settings tab. */
3026
+ reflect(owner, reason, cancel) {
3027
+ const store = this.deps.stores(owner.chat);
3028
+ if (store === void 0) return;
3029
+ this.reflecting.add(owner.chat);
3030
+ this.deps.track(owner.chat, this.deps.boundaries().reflector.reflect({
3031
+ chat: owner.chat,
3032
+ turn: owner.turn,
3033
+ store,
3034
+ reason
3035
+ }, cancel).then((report) => {
3036
+ if (report.characters.length > 0) this.deps.written(owner.chat);
3037
+ }).catch((error) => {
3038
+ if (cancel.aborted) return;
3039
+ recordFailure(store.story, messageOf(error));
3040
+ this.deps.problem(`what the characters believe was not sorted: ${messageOf(error)}`);
3041
+ }).finally(() => {
3042
+ this.reflecting.delete(owner.chat);
3043
+ }));
2969
3044
  }
2970
3045
  /** Fit what was made up into the rest of the world, when enough of it is waiting or some has waited long. */
2971
3046
  consolidate(owner, cancel) {
@@ -3021,36 +3096,94 @@ var AfterTurnJobs = class {
3021
3096
  }));
3022
3097
  }
3023
3098
  };
3024
- //#endregion
3025
- //#region src/host/orchestration/whereabouts.ts
3026
- const within = (inner, outer, places) => {
3027
- const byId = new Map(places.map((place) => [place.id, place]));
3028
- const seen = /* @__PURE__ */ new Set();
3029
- for (let at = inner; at !== void 0 && !seen.has(at.id); at = at.parentId === void 0 ? void 0 : byId.get(at.parentId)) {
3030
- if (at.id === outer.id) return true;
3031
- seen.add(at.id);
3032
- }
3033
- return false;
3034
- };
3035
3099
  /**
3036
- * Compares the place an action is said to happen at (by key) with where the character is. Only a proven mismatch counts: a character that is
3037
- * nowhere, or a world without places, is no evidence, and a place that contains the other (a room and its building) is the same for this.
3100
+ * What the characters away from the player decide about what fell due, one commitment after another: their activity, and a move to where the commitment was when they
3101
+ * mean to keep it. It is recorded as a round only they perceive, and the keeper writes it.
3038
3102
  */
3039
- function whereabouts(places, here, at) {
3040
- const target = places.find((place) => locationKey(place) === at);
3041
- if (target === void 0) return { kind: "unknown" };
3042
- if (here === void 0) return { kind: "unplaced" };
3043
- return within(here, target, places) || within(target, here, places) ? { kind: "here" } : {
3044
- kind: "elsewhere",
3045
- target,
3046
- here
3047
- };
3103
+ async function runOffScene(deps, owner, state, store, due, limit) {
3104
+ const { summary, perCharacter, joint } = store.settings().offstage;
3105
+ let budget = limit;
3106
+ const acted = /* @__PURE__ */ new Map();
3107
+ for (const item of due) {
3108
+ if (budget <= 0) break;
3109
+ const cast = store.cast();
3110
+ const keys = item.characters.filter((key) => cast.some((member) => member.key === key) && (acted.get(key) ?? 0) < perCharacter).slice(0, budget);
3111
+ if (keys.length === 0) continue;
3112
+ budget -= keys.length;
3113
+ for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
3114
+ const reports = [];
3115
+ for (const group of joint ? keys.map((key) => [key]) : [keys]) {
3116
+ const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
3117
+ const asked = {
3118
+ ...state,
3119
+ situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
3120
+ history: [],
3121
+ recalled: /* @__PURE__ */ new Map()
3122
+ };
3123
+ delete asked.first;
3124
+ delete asked.second;
3125
+ reports.push(...(await deps.ask(group, cast, asked, summary)).reports);
3126
+ }
3127
+ if (reports.length === 0) continue;
3128
+ const where = item.place;
3129
+ const moves = new Map(reports.flatMap((report) => {
3130
+ if (report.commitment === "low" || where === void 0) return [];
3131
+ const check = store.checkMove(report.character, {
3132
+ location: where,
3133
+ ignoreExits: true
3134
+ });
3135
+ return check.ok ? [[report.character, check]] : [];
3136
+ }));
3137
+ store.commit(reports.flatMap((report) => {
3138
+ const member = cast.find((candidate) => candidate.key === report.character);
3139
+ const move = moves.get(report.character);
3140
+ return member === void 0 ? [] : [{
3141
+ character: member.character.id,
3142
+ patch: { activity: report.intent },
3143
+ ...move?.ok === true ? { move: move.move } : {}
3144
+ }];
3145
+ }));
3146
+ state.offstage += 1;
3147
+ const time = store.time(owner.turn);
3148
+ store.queueCommit({
3149
+ turn: owner.turn,
3150
+ round: 100 + state.offstage,
3151
+ situation: item.text,
3152
+ offstage: true,
3153
+ time: {
3154
+ from: time.now,
3155
+ to: time.now,
3156
+ zone: time.zone
3157
+ },
3158
+ entries: reports.map((report) => {
3159
+ const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
3160
+ const move = moves.get(report.character);
3161
+ return {
3162
+ character: report.character,
3163
+ name: report.name,
3164
+ intent: report.intent,
3165
+ commitment: report.commitment,
3166
+ result: "succeeded",
3167
+ summary: report.intent,
3168
+ spoken: false,
3169
+ ...at === void 0 ? {} : { at: {
3170
+ key: locationKey(at),
3171
+ name: at.name
3172
+ } },
3173
+ ...move?.ok === true && move.plan.from !== move.move.to ? { moved: { ...move.to } } : {}
3174
+ };
3175
+ })
3176
+ });
3177
+ store.markHandled([item.key]);
3178
+ deps.write();
3179
+ if (summary && deps.stillThis()) {
3180
+ const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3181
+ store.addNote("away", owner.turn, lines);
3182
+ }
3183
+ }
3048
3184
  }
3049
3185
  //#endregion
3050
- //#region src/host/orchestration/turn-engine.ts
3051
- const MAX_OBJECTIONS = 3;
3052
- /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
3053
- const MAX_ROUND_SECONDS = 86400;
3186
+ //#region src/host/orchestration/turn-text.ts
3054
3187
  /**
3055
3188
  * A model sometimes sends who speaks as a segment of its own (an utterance with no character whose text is the character's key or name) followed by the words with no
3056
3189
  * character either. When the label is exactly a character of the scene, the label is folded into the words that follow it.
@@ -3099,6 +3232,162 @@ function repeatsEarlier(signature, asked) {
3099
3232
  return union === 0 || shared / union >= SAME_SITUATION;
3100
3233
  });
3101
3234
  }
3235
+ /** The words as the character said them, whatever quotes the game master put around them. */
3236
+ function asSpoken(segments, spoken) {
3237
+ const left = [...spoken];
3238
+ return segments.map((segment) => {
3239
+ if (segment.type !== "utterance") return segment;
3240
+ const at = left.findIndex((said) => said.character === segment.character && sameWords(said.text, segment.text));
3241
+ return at === -1 ? segment : {
3242
+ ...segment,
3243
+ text: left.splice(at, 1)[0].text
3244
+ };
3245
+ });
3246
+ }
3247
+ //#endregion
3248
+ //#region src/host/orchestration/turn-rules.ts
3249
+ /** Whether the game master still has to judge the player's action. */
3250
+ function judgeDue(state) {
3251
+ return state.judgeWanted === true && state.phase === "idle" && state.ooc === void 0 && state.judgement === void 0;
3252
+ }
3253
+ /** Why an out-of-character command may not change anything yet, when it may not. */
3254
+ function oocBlock(state) {
3255
+ if (state.ooc === void 0) return void 0;
3256
+ if (state.ooc.question === true) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3257
+ if (state.ooc.ruling === void 0) return "this turn is an out-of-character command: rule on it first with ooc_ruling";
3258
+ return state.ooc.ruling.legal ? void 0 : "the command was refused: nothing changes; call narrate with no segments to tell the player";
3259
+ }
3260
+ /** Whether the chat wants a preview of the scene and the game master has not shown it yet. */
3261
+ function previewDue(state) {
3262
+ return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
3263
+ }
3264
+ function explainPhase(state, attempted) {
3265
+ if (state.ooc?.question === true && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3266
+ 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";
3267
+ const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
3268
+ switch (state.phase) {
3269
+ 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";
3270
+ 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)}`;
3271
+ 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)}`;
3272
+ 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)}`;
3273
+ case "done": return "this turn is already recorded";
3274
+ case "skipped": return "this turn needs no round";
3275
+ }
3276
+ }
3277
+ function canContinue(state) {
3278
+ const left = (state.limit ?? 0) - state.rounds;
3279
+ return left > 0 ? `, or call activate_characters if the story genuinely needs them again (${left} round(s) left)` : "";
3280
+ }
3281
+ function mustSay(state) {
3282
+ return state.utterances.length === 0 ? "" : `; it must carry these utterances exactly, in this order: ${state.utterances.map((utterance) => `${utterance.name}: "${utterance.text}"`).join(" | ")}`;
3283
+ }
3284
+ /** `player` is the key of the player's character when an outcome for it is acceptable: it is not asked to act, but what it did can move it or have it handle things. */
3285
+ function checkOutcomes(attempt, outcomes, store, player, decreed) {
3286
+ const expected = decreed === void 0 ? attempt.reports.map((report) => report.character) : [...new Set(outcomes.map((outcome) => outcome.character))];
3287
+ const unknown = decreed === void 0 ? [] : [...new Set(outcomes.map((outcome) => outcome.character))].filter((key) => !decreed.some((member) => member.key === key)).map((key) => `${key} is not a character of the story`);
3288
+ const given = outcomes.filter((outcome) => outcome.character !== player).map((outcome) => outcome.character);
3289
+ const problems = [
3290
+ ...unknown,
3291
+ ...outcomes.filter((outcome) => outcome.character === player).length > 1 ? [`more than one outcome for ${player}`] : [],
3292
+ ...expected.filter((key) => !given.includes(key)).map((key) => `missing an outcome for ${key}`),
3293
+ ...[...new Set(given.filter((key) => !expected.includes(key)))].map((key) => `${key} is not waiting for an outcome`),
3294
+ ...[...new Set(given.filter((key, index) => given.indexOf(key) !== index))].map((key) => `more than one outcome for ${key}`),
3295
+ ...outcomes.filter((outcome) => !RESULTS.includes(outcome.result)).map((outcome) => `${outcome.character}: unknown result "${outcome.result}"`),
3296
+ ...outcomes.filter((outcome) => outcome.summary.trim() === "").map((outcome) => `${outcome.character}: say what happens`),
3297
+ ...outcomes.flatMap((outcome) => moveProblems(outcome, store)),
3298
+ ...itemProblems(outcomes, store),
3299
+ ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`))
3300
+ ];
3301
+ if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} (expected exactly: ${expected.join(", ")})`);
3302
+ }
3303
+ /** Why a character cannot go where the outcome sends it, if it cannot: the game master hears it before the round is recorded. */
3304
+ function moveProblems(outcome, store) {
3305
+ if (outcome.moveTo === void 0) return [];
3306
+ if (outcome.result === "failed") return [`${outcome.character}: its intent failed, so it does not go anywhere: leave moves_to out`];
3307
+ const checked = store.checkMove(outcome.character, outcome.moveTo);
3308
+ return checked.ok ? [] : checked.problems.map((problem) => `${outcome.character}: cannot go to ${outcome.moveTo?.location}: ${problem}`);
3309
+ }
3310
+ /** Why what the outcomes do with things cannot be done, if it cannot: tried in order, each seeing what the one before did. */
3311
+ function itemProblems(outcomes, store) {
3312
+ const entries = outcomes.flatMap((outcome) => outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 || outcome.result === "failed" ? [] : [{
3313
+ character: outcome.character,
3314
+ changes: outcome.itemChanges
3315
+ }]);
3316
+ const failed = outcomes.filter((outcome) => outcome.result === "failed" && (outcome.itemChanges?.length ?? 0) > 0).map((outcome) => `${outcome.character}: its intent failed, so it does nothing with things: leave item_changes out`);
3317
+ if (entries.length === 0) return failed;
3318
+ const checked = store.checkItemChanges(entries);
3319
+ return checked.ok ? failed : [...failed, ...checked.problems];
3320
+ }
3321
+ /** What the world made a character notice: taken up in the first attempt of a round, and told the same again on the retry. */
3322
+ function cuesOf(state, key, member, store, attempt) {
3323
+ if (attempt === 2 || store === void 0) return state.cues.get(key) ?? [];
3324
+ const pending = store.cuesFor(member.character.id);
3325
+ if (pending.length === 0) return [];
3326
+ store.doneCues(pending.map((cue) => cue.id));
3327
+ const texts = pending.map((cue) => cue.text);
3328
+ state.cues.set(key, texts);
3329
+ return texts;
3330
+ }
3331
+ /** How a character sees people present or explicitly in the moment, for those it has a profile of. */
3332
+ function knownRelationships(member, company, situation, cast, store) {
3333
+ const present = new Set(company.map((candidate) => candidate.character.id));
3334
+ const relevant = mentioned(situation, cast.map((candidate) => candidate.character));
3335
+ return store.story.relationships.from(member.character.id).flatMap((relation) => {
3336
+ if (!present.has(relation.toId) && !relevant.has(relation.toId)) return [];
3337
+ const other = cast.find((candidate) => candidate.character.id === relation.toId);
3338
+ return other === void 0 || other.key === member.key ? [] : [{
3339
+ name: referent(other.character),
3340
+ label: relation.label,
3341
+ summary: relation.summary,
3342
+ present: present.has(relation.toId),
3343
+ familiarity: relation.familiarity,
3344
+ trust: relation.trust,
3345
+ affinity: relation.affinity,
3346
+ tension: relation.tension
3347
+ }];
3348
+ });
3349
+ }
3350
+ function reactions(state) {
3351
+ const first = state.first;
3352
+ return (first?.outcomes ?? []).flatMap((outcome) => {
3353
+ const report = first?.reports.find((candidate) => candidate.character === outcome.character);
3354
+ return report === void 0 ? [] : [{
3355
+ character: report.character,
3356
+ name: report.name,
3357
+ intent: report.intent,
3358
+ ...report.utterance === void 0 ? {} : { utterance: report.utterance },
3359
+ result: outcome.result,
3360
+ summary: outcome.summary
3361
+ }];
3362
+ });
3363
+ }
3364
+ /** The final decision for each character of the round: the retry's replaces the first attempt's. */
3365
+ /** The player's character is never asked to act, so what the game master decided it did stands in for its report. */
3366
+ function playerReport(state, outcome) {
3367
+ const member = state.cast.find((candidate) => candidate.key === outcome.character && candidate.character.control === "player");
3368
+ return member === void 0 ? void 0 : {
3369
+ character: member.key,
3370
+ name: member.character.name,
3371
+ intent: outcome.summary,
3372
+ commitment: "high"
3373
+ };
3374
+ }
3375
+ function decisions(state) {
3376
+ const decided = /* @__PURE__ */ new Map();
3377
+ for (const attempt of [state.first, state.second]) for (const outcome of attempt?.outcomes ?? []) {
3378
+ const report = attempt?.reports.find((candidate) => candidate.character === outcome.character) ?? playerReport(state, outcome);
3379
+ if (report !== void 0) decided.set(outcome.character, {
3380
+ outcome,
3381
+ report
3382
+ });
3383
+ }
3384
+ return decided;
3385
+ }
3386
+ //#endregion
3387
+ //#region src/host/orchestration/turn-engine.ts
3388
+ const MAX_OBJECTIONS = 3;
3389
+ /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
3390
+ const MAX_ROUND_SECONDS = 86400;
3102
3391
  /** The game master is asked to correct its output this many times before it is corrected for it. */
3103
3392
  const MAX_REFUSALS = 2;
3104
3393
  /** 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. */
@@ -3126,6 +3415,8 @@ var TurnEngine = class {
3126
3415
  /** What runs in the background of each chat and writes to its story, other than the records: fitting in what was made up, and the characters away. */
3127
3416
  working = /* @__PURE__ */ new Map();
3128
3417
  afterTurn;
3418
+ /** What a reflection the player asked for is cancelled with, as `stop` does for the turn. */
3419
+ reflectionCancels = /* @__PURE__ */ new Map();
3129
3420
  /** Chats whose characters away from the player are being asked about what fell due: one run at a time. */
3130
3421
  offstage = /* @__PURE__ */ new Set();
3131
3422
  constructor(boundaries, stores, problem = () => void 0, written = () => void 0) {
@@ -3196,7 +3487,7 @@ var TurnEngine = class {
3196
3487
  }, store.story, signal);
3197
3488
  const place = member.place === void 0 ? void 0 : store.place(member.place.location.id);
3198
3489
  const company = place === void 0 ? cast : place.here;
3199
- const relationships = this.knownRelationships(member, company, question, cast, store);
3490
+ const relationships = knownRelationships(member, company, question, cast, store);
3200
3491
  const carrying = store.carried(member.character.id);
3201
3492
  const affiliations = store.affiliations(member.character.id);
3202
3493
  const tracked = store.trackedFor(member.character.id, company.map((entry) => entry.character.id));
@@ -3280,17 +3571,6 @@ var TurnEngine = class {
3280
3571
  expectJudgement(owner) {
3281
3572
  this.stateFor(owner).judgeWanted = true;
3282
3573
  }
3283
- /** Whether the game master still has to judge the player's action. */
3284
- judgeDue(state) {
3285
- return state.judgeWanted === true && state.phase === "idle" && state.ooc === void 0 && state.judgement === void 0;
3286
- }
3287
- /** Why an out-of-character command may not change anything yet, when it may not. */
3288
- oocBlock(state) {
3289
- if (state.ooc === void 0) return void 0;
3290
- if (state.ooc.question === true) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3291
- if (state.ooc.ruling === void 0) return "this turn is an out-of-character command: rule on it first with ooc_ruling";
3292
- return state.ooc.ruling.legal ? void 0 : "the command was refused: nothing changes; call narrate with no segments to tell the player";
3293
- }
3294
3574
  /** Mark a turn as one that needs no round, for example because the player's input was refused. */
3295
3575
  skip(owner) {
3296
3576
  this.stateFor(owner).phase = "skipped";
@@ -3302,10 +3582,10 @@ var TurnEngine = class {
3302
3582
  async activate(owner, input, run, signal) {
3303
3583
  const state = this.stateFor(owner);
3304
3584
  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");
3305
- if (state.phase !== "idle" && state.phase !== "between") throw new Error(this.explain(state, "activate_characters"));
3306
- if (this.judgeDue(state)) throw new Error(this.explain(state, "activate_characters"));
3585
+ if (state.phase !== "idle" && state.phase !== "between") throw new Error(explainPhase(state, "activate_characters"));
3586
+ if (judgeDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3307
3587
  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`);
3308
- if (this.previewDue(state)) throw new Error(this.explain(state, "activate_characters"));
3588
+ if (previewDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3309
3589
  const store = this.storeOf(owner);
3310
3590
  const limit = store.settings().maxRounds;
3311
3591
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} of characters were already played for this message, which is the most this chat allows: deliver the output with narrate`);
@@ -3352,14 +3632,14 @@ var TurnEngine = class {
3352
3632
  const store = this.storeOf(owner);
3353
3633
  if (state.ooc !== void 0) return { done: this.decree(owner, state, outcomes, elapsedSeconds) };
3354
3634
  if (state.phase === "idle" || state.phase === "between") {
3355
- if (this.judgeDue(state) || this.previewDue(state)) throw new Error(this.explain(state, "resolve_round"));
3635
+ if (judgeDue(state) || previewDue(state)) throw new Error(explainPhase(state, "resolve_round"));
3356
3636
  const player = store.cast().find((member) => member.character.control === "player");
3357
3637
  if (player !== void 0 && outcomes.length === 1 && outcomes[0]?.character === player.key) return { done: this.resolvePlayer(owner, state, outcomes[0], elapsedSeconds) };
3358
3638
  }
3359
- if (state.phase !== "resolving" && state.phase !== "retrying") throw new Error(this.explain(state, "resolve_round"));
3639
+ if (state.phase !== "resolving" && state.phase !== "retrying") throw new Error(explainPhase(state, "resolve_round"));
3360
3640
  const attempt = state.phase === "resolving" ? state.first : state.second;
3361
3641
  if (attempt === void 0) throw new Error("internal: no round to resolve");
3362
- this.check(attempt, outcomes, store, state.phase === "resolving" ? this.playerKey(state) : void 0);
3642
+ checkOutcomes(attempt, outcomes, store, state.phase === "resolving" ? this.playerKey(state) : void 0);
3363
3643
  if (elapsedSeconds !== void 0) state.elapsed = this.elapsedChecked(owner, elapsedSeconds);
3364
3644
  attempt.outcomes = [...outcomes];
3365
3645
  if (state.phase === "resolving") {
@@ -3389,14 +3669,14 @@ var TurnEngine = class {
3389
3669
  * @throws {Error} when the command was not ruled legal, the limit of rounds is reached, or an outcome is not acceptable.
3390
3670
  */
3391
3671
  decree(owner, state, outcomes, elapsedSeconds) {
3392
- const blocked = this.oocBlock(state);
3672
+ const blocked = oocBlock(state);
3393
3673
  if (blocked !== void 0) throw new Error(blocked);
3394
3674
  const store = this.storeOf(owner);
3395
3675
  const limit = store.settings().maxRounds;
3396
3676
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} were already decreed for this command, which is the most this chat allows: deliver the output with narrate`);
3397
3677
  state.cast = store.cast();
3398
3678
  if (outcomes.length === 0) throw new Error("decree at least one outcome");
3399
- this.check({
3679
+ checkOutcomes({
3400
3680
  reports: [],
3401
3681
  failures: []
3402
3682
  }, outcomes, store, void 0, state.cast);
@@ -3435,7 +3715,7 @@ var TurnEngine = class {
3435
3715
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} were already played for this message, which is the most this chat allows: deliver the output with narrate`);
3436
3716
  state.cast = store.cast();
3437
3717
  const player = state.cast.find((member) => member.key === outcome.character);
3438
- this.check({
3718
+ checkOutcomes({
3439
3719
  reports: [],
3440
3720
  failures: []
3441
3721
  }, [outcome], store, outcome.character);
@@ -3458,7 +3738,7 @@ var TurnEngine = class {
3458
3738
  preview(owner, text) {
3459
3739
  const state = this.stateFor(owner);
3460
3740
  if (state.ooc !== void 0) throw new Error("an out-of-character turn shows no preview: go on with " + (state.ooc.question === true ? "ooc_answer" : "ooc_ruling"));
3461
- if (this.judgeDue(state)) throw new Error("judge the action first with judge_action");
3741
+ if (judgeDue(state)) throw new Error("judge the action first with judge_action");
3462
3742
  if (!this.storeOf(owner).settings().preview.enabled) throw new Error("this chat shows no preview: go on with activate_characters");
3463
3743
  if (state.previewed) throw new Error("a preview was already shown for this message: go on with activate_characters");
3464
3744
  if (state.phase !== "idle") throw new Error("the preview comes first, before the characters are asked");
@@ -3494,8 +3774,8 @@ var TurnEngine = class {
3494
3774
  advanceTime(owner, request) {
3495
3775
  const state = this.stateFor(owner);
3496
3776
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: time is skipped between rounds, not in the middle of one");
3497
- if (state.phase === "done" || state.phase === "skipped") throw new Error(this.explain(state, void 0));
3498
- const blocked = this.oocBlock(state);
3777
+ if (state.phase === "done" || state.phase === "skipped") throw new Error(explainPhase(state, void 0));
3778
+ const blocked = oocBlock(state);
3499
3779
  if (blocked !== void 0) throw new Error(blocked);
3500
3780
  try {
3501
3781
  return {
@@ -3515,7 +3795,7 @@ var TurnEngine = class {
3515
3795
  */
3516
3796
  async narrate(owner, segments, run, addressed = []) {
3517
3797
  const state = this.stateFor(owner);
3518
- if (state.phase !== "between") throw new Error(this.explain(state, "narrate"));
3798
+ if (state.phase !== "between") throw new Error(explainPhase(state, "narrate"));
3519
3799
  const pending = new Set(this.storeOf(owner).pendingBeats().map((beat) => beat.id));
3520
3800
  const unknown = addressed.filter((id) => !pending.has(id));
3521
3801
  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)`);
@@ -3559,7 +3839,7 @@ var TurnEngine = class {
3559
3839
  async expand(owner, input, signal) {
3560
3840
  const state = this.stateFor(owner);
3561
3841
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: the world is extended between rounds, not in the middle of one");
3562
- const blocked = this.oocBlock(state);
3842
+ const blocked = oocBlock(state);
3563
3843
  if (blocked !== void 0) throw new Error(blocked);
3564
3844
  const need = AUTHORING_NEEDS.find((candidate) => candidate === input.need);
3565
3845
  if (need === void 0) throw new Error(`"${input.need}" is not a reason to make something up; the reasons are: ${AUTHORING_NEEDS.join(", ")}`);
@@ -3586,7 +3866,7 @@ var TurnEngine = class {
3586
3866
  introduce(owner, input) {
3587
3867
  const state = this.stateFor(owner);
3588
3868
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: things are introduced between rounds, not in the middle of one");
3589
- const blocked = this.oocBlock(state);
3869
+ const blocked = oocBlock(state);
3590
3870
  if (blocked !== void 0) throw new Error(blocked);
3591
3871
  const name = input.name.trim();
3592
3872
  if (name === "") throw new Error("name the thing");
@@ -3648,93 +3928,20 @@ var TurnEngine = class {
3648
3928
  this.offstage.delete(owner.chat);
3649
3929
  }));
3650
3930
  }
3651
- async runOffScene(owner, state, store, due, limit, run) {
3652
- const { summary, perCharacter, joint } = store.settings().offstage;
3653
- let budget = limit;
3654
- const acted = /* @__PURE__ */ new Map();
3655
- for (const item of due) {
3656
- if (budget <= 0) break;
3657
- const cast = store.cast();
3658
- const keys = item.characters.filter((key) => cast.some((member) => member.key === key) && (acted.get(key) ?? 0) < perCharacter).slice(0, budget);
3659
- if (keys.length === 0) continue;
3660
- budget -= keys.length;
3661
- for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
3662
- const reports = [];
3663
- for (const group of joint ? keys.map((key) => [key]) : [keys]) {
3664
- const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
3665
- const asked = {
3666
- ...state,
3667
- situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
3668
- history: [],
3669
- recalled: /* @__PURE__ */ new Map()
3670
- };
3671
- delete asked.first;
3672
- delete asked.second;
3673
- reports.push(...(await this.runAttempt(owner, 1, group, cast, asked, run, state.cancel.signal, summary)).reports);
3674
- }
3675
- if (reports.length === 0) continue;
3676
- const where = item.place;
3677
- const moves = new Map(reports.flatMap((report) => {
3678
- if (report.commitment === "low" || where === void 0) return [];
3679
- const check = store.checkMove(report.character, {
3680
- location: where,
3681
- ignoreExits: true
3682
- });
3683
- return check.ok ? [[report.character, check]] : [];
3684
- }));
3685
- store.commit(reports.flatMap((report) => {
3686
- const member = cast.find((candidate) => candidate.key === report.character);
3687
- const move = moves.get(report.character);
3688
- return member === void 0 ? [] : [{
3689
- character: member.character.id,
3690
- patch: { activity: report.intent },
3691
- ...move?.ok === true ? { move: move.move } : {}
3692
- }];
3693
- }));
3694
- state.offstage += 1;
3695
- const time = store.time(owner.turn);
3696
- store.queueCommit({
3697
- turn: owner.turn,
3698
- round: 100 + state.offstage,
3699
- situation: item.text,
3700
- offstage: true,
3701
- time: {
3702
- from: time.now,
3703
- to: time.now,
3704
- zone: time.zone
3705
- },
3706
- entries: reports.map((report) => {
3707
- const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
3708
- const move = moves.get(report.character);
3709
- return {
3710
- character: report.character,
3711
- name: report.name,
3712
- intent: report.intent,
3713
- commitment: report.commitment,
3714
- result: "succeeded",
3715
- summary: report.intent,
3716
- spoken: false,
3717
- ...at === void 0 ? {} : { at: {
3718
- key: locationKey(at),
3719
- name: at.name
3720
- } },
3721
- ...move?.ok === true && move.plan.from !== move.move.to ? { moved: { ...move.to } } : {}
3722
- };
3723
- })
3724
- });
3725
- store.markHandled([item.key]);
3726
- this.write(owner, state);
3727
- if (summary && this.states.get(owner.chat) === state) {
3728
- const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3729
- store.addNote("away", owner.turn, lines);
3730
- }
3731
- }
3931
+ runOffScene(owner, state, store, due, limit, run) {
3932
+ return runOffScene({
3933
+ ask: (group, cast, asked, summary) => this.runAttempt(owner, 1, group, cast, asked, run, state.cancel.signal, summary),
3934
+ write: () => {
3935
+ this.write(owner, state);
3936
+ },
3937
+ stillThis: () => this.states.get(owner.chat) === state
3938
+ }, owner, state, store, due, limit);
3732
3939
  }
3733
3940
  /** What still has to happen before the turn may end, or nothing when it may. */
3734
3941
  missing(owner) {
3735
3942
  const state = this.stateFor(owner);
3736
3943
  if (state.phase === "done" || state.phase === "skipped") return void 0;
3737
- return this.explain(state, void 0);
3944
+ return explainPhase(state, void 0);
3738
3945
  }
3739
3946
  /** Wait until the records being written are written or have failed. */
3740
3947
  async flush(owner) {
@@ -3761,6 +3968,36 @@ var TurnEngine = class {
3761
3968
  await this.chains.get(chat);
3762
3969
  }
3763
3970
  }
3971
+ /**
3972
+ * Starts a reflection the player asked for: the records still waiting are written first, so that what the characters took in is there to
3973
+ * sort, and the pass then runs in the background. @throws {ReflectionRefusedError} while a turn is being played, or when a pass is already running.
3974
+ */
3975
+ async reflect(chat) {
3976
+ const store = this.stores(chat);
3977
+ if (store === void 0) throw new Error(`no story for chat ${chat}`);
3978
+ const turning = this.states.get(chat);
3979
+ if (turning !== void 0 && [
3980
+ "resolving",
3981
+ "retrying",
3982
+ "between"
3983
+ ].includes(turning.phase)) throw new ReflectionRefusedError("a turn is being played; reflect when it is over");
3984
+ const delivered = this.delivered.get(chat);
3985
+ if (delivered !== void 0 && store.pendingCommits().length > 0) this.write({
3986
+ chat,
3987
+ turn: delivered.turn
3988
+ }, delivered);
3989
+ await this.chains.get(chat);
3990
+ const cancel = new AbortController();
3991
+ this.reflectionCancels.set(chat, cancel);
3992
+ this.afterTurn.reflectNow({
3993
+ chat,
3994
+ turn: store.story.metadata.get().turns
3995
+ }, cancel.signal);
3996
+ }
3997
+ /** Whether a reflection is running for the chat. */
3998
+ reflecting(chat) {
3999
+ return this.afterTurn.isReflecting(chat);
4000
+ }
3764
4001
  /** Wait until the run of the keeper in flight, if any, has ended; nothing is started. */
3765
4002
  async idle(chat) {
3766
4003
  await this.chains.get(chat);
@@ -3787,6 +4024,7 @@ var TurnEngine = class {
3787
4024
  /** Stops what the turn of a chat has in flight: nothing it started is cancelled halfway through a write, but nothing new is asked of a model. */
3788
4025
  stop(chat) {
3789
4026
  this.states.get(chat)?.cancel.abort();
4027
+ this.reflectionCancels.get(chat)?.abort();
3790
4028
  }
3791
4029
  /** Resolves when nothing of the chat writes to its story any more: the records, what was made up being fitted in, the characters away. */
3792
4030
  async quiesce(chat) {
@@ -3798,6 +4036,8 @@ var TurnEngine = class {
3798
4036
  }
3799
4037
  forget(chat) {
3800
4038
  this.states.get(chat)?.cancel.abort();
4039
+ this.reflectionCancels.get(chat)?.abort();
4040
+ this.reflectionCancels.delete(chat);
3801
4041
  this.states.delete(chat);
3802
4042
  this.chains.delete(chat);
3803
4043
  this.delivered.delete(chat);
@@ -3839,72 +4079,11 @@ var TurnEngine = class {
3839
4079
  if (store === void 0) throw new Error("this chat is not a roleplay session");
3840
4080
  return store;
3841
4081
  }
3842
- /** Whether the chat wants a preview of the scene and the game master has not shown it yet. */
3843
- previewDue(state) {
3844
- return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
3845
- }
3846
- explain(state, attempted) {
3847
- if (state.ooc?.question === true && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3848
- 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";
3849
- const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
3850
- switch (state.phase) {
3851
- case "idle": return this.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" : this.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";
3852
- 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)}`;
3853
- 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)}`;
3854
- 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${this.mustSay(state)}${this.canContinue(state)}`;
3855
- case "done": return "this turn is already recorded";
3856
- case "skipped": return "this turn needs no round";
3857
- }
3858
- }
3859
- canContinue(state) {
3860
- const left = (state.limit ?? 0) - state.rounds;
3861
- return left > 0 ? `, or call activate_characters if the story genuinely needs them again (${left} round(s) left)` : "";
3862
- }
3863
- mustSay(state) {
3864
- return state.utterances.length === 0 ? "" : `; it must carry these utterances exactly, in this order: ${state.utterances.map((utterance) => `${utterance.name}: "${utterance.text}"`).join(" | ")}`;
3865
- }
3866
- /** `player` is the key of the player's character when an outcome for it is acceptable: it is not asked to act, but what it did can move it or have it handle things. */
3867
- check(attempt, outcomes, store, player, decreed) {
3868
- const expected = decreed === void 0 ? attempt.reports.map((report) => report.character) : [...new Set(outcomes.map((outcome) => outcome.character))];
3869
- const unknown = decreed === void 0 ? [] : [...new Set(outcomes.map((outcome) => outcome.character))].filter((key) => !decreed.some((member) => member.key === key)).map((key) => `${key} is not a character of the story`);
3870
- const given = outcomes.filter((outcome) => outcome.character !== player).map((outcome) => outcome.character);
3871
- const problems = [
3872
- ...unknown,
3873
- ...outcomes.filter((outcome) => outcome.character === player).length > 1 ? [`more than one outcome for ${player}`] : [],
3874
- ...expected.filter((key) => !given.includes(key)).map((key) => `missing an outcome for ${key}`),
3875
- ...[...new Set(given.filter((key) => !expected.includes(key)))].map((key) => `${key} is not waiting for an outcome`),
3876
- ...[...new Set(given.filter((key, index) => given.indexOf(key) !== index))].map((key) => `more than one outcome for ${key}`),
3877
- ...outcomes.filter((outcome) => !RESULTS.includes(outcome.result)).map((outcome) => `${outcome.character}: unknown result "${outcome.result}"`),
3878
- ...outcomes.filter((outcome) => outcome.summary.trim() === "").map((outcome) => `${outcome.character}: say what happens`),
3879
- ...outcomes.flatMap((outcome) => this.moveProblems(outcome, store)),
3880
- ...this.itemProblems(outcomes, store),
3881
- ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`))
3882
- ];
3883
- if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} (expected exactly: ${expected.join(", ")})`);
3884
- }
3885
- /** Why a character cannot go where the outcome sends it, if it cannot: the game master hears it before the round is recorded. */
3886
- moveProblems(outcome, store) {
3887
- if (outcome.moveTo === void 0) return [];
3888
- if (outcome.result === "failed") return [`${outcome.character}: its intent failed, so it does not go anywhere: leave moves_to out`];
3889
- const checked = store.checkMove(outcome.character, outcome.moveTo);
3890
- return checked.ok ? [] : checked.problems.map((problem) => `${outcome.character}: cannot go to ${outcome.moveTo?.location}: ${problem}`);
3891
- }
3892
- /** Why what the outcomes do with things cannot be done, if it cannot: tried in order, each seeing what the one before did. */
3893
- itemProblems(outcomes, store) {
3894
- const entries = outcomes.flatMap((outcome) => outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 || outcome.result === "failed" ? [] : [{
3895
- character: outcome.character,
3896
- changes: outcome.itemChanges
3897
- }]);
3898
- const failed = outcomes.filter((outcome) => outcome.result === "failed" && (outcome.itemChanges?.length ?? 0) > 0).map((outcome) => `${outcome.character}: its intent failed, so it does nothing with things: leave item_changes out`);
3899
- if (entries.length === 0) return failed;
3900
- const checked = store.checkItemChanges(entries);
3901
- return checked.ok ? failed : [...failed, ...checked.problems];
3902
- }
3903
4082
  /** Every character acts at the same time; one that fails or answers badly is reported, not fatal. */
3904
4083
  async runAttempt(owner, number, keys, cast, state, run, signal, away = false) {
3905
4084
  const store = this.stores(owner.chat);
3906
4085
  const { outputValidator } = this.boundaries();
3907
- const reaction = number === 2 ? this.reactions(state) : void 0;
4086
+ const reaction = number === 2 ? reactions(state) : void 0;
3908
4087
  const queryVector = number === 1 && store !== void 0 ? await store.queryVector(state.situation, signal) : void 0;
3909
4088
  const time = store?.time(owner.turn);
3910
4089
  const answers = await Promise.all(keys.map(async (key) => {
@@ -3925,12 +4104,12 @@ var TurnEngine = class {
3925
4104
  }, store.story, signal) : state.recalled.get(key) ?? [];
3926
4105
  if (number === 1 && memories.length > 0) state.recalled.set(key, memories);
3927
4106
  const place = member.place === void 0 ? void 0 : store?.place(member.place.location.id);
3928
- const relationships = store === void 0 ? [] : this.knownRelationships(member, place === void 0 ? cast : place.here, state.situation, cast, store);
4107
+ const relationships = store === void 0 ? [] : knownRelationships(member, place === void 0 ? cast : place.here, state.situation, cast, store);
3929
4108
  const carrying = store === void 0 ? [] : store.carried(member.character.id);
3930
4109
  const knowledge = store?.knowledge(member.character.id, owner.turn, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
3931
4110
  const affiliations = store?.affiliations(member.character.id) ?? [];
3932
4111
  const agenda = store?.agenda(owner.turn, member.character.id);
3933
- const cues = this.cuesOf(state, key, member, store, number);
4112
+ const cues = cuesOf(state, key, member, store, number);
3934
4113
  const upcoming = store?.upcomingFor(member.character.id, owner.turn) ?? [];
3935
4114
  const tracked = store?.trackedFor(member.character.id, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
3936
4115
  const request = {
@@ -3991,74 +4170,9 @@ var TurnEngine = class {
3991
4170
  failures: answers.filter((answer) => "reason" in answer)
3992
4171
  };
3993
4172
  }
3994
- /** What the world made a character notice: taken up in the first attempt of a round, and told the same again on the retry. */
3995
- cuesOf(state, key, member, store, attempt) {
3996
- if (attempt === 2 || store === void 0) return state.cues.get(key) ?? [];
3997
- const pending = store.cuesFor(member.character.id);
3998
- if (pending.length === 0) return [];
3999
- store.doneCues(pending.map((cue) => cue.id));
4000
- const texts = pending.map((cue) => cue.text);
4001
- state.cues.set(key, texts);
4002
- return texts;
4003
- }
4004
- /** How a character sees people present or explicitly in the moment, for those it has a profile of. */
4005
- knownRelationships(member, company, situation, cast, store) {
4006
- const present = new Set(company.map((candidate) => candidate.character.id));
4007
- const relevant = mentioned(situation, cast.map((candidate) => candidate.character));
4008
- return store.story.relationships.from(member.character.id).flatMap((relation) => {
4009
- if (!present.has(relation.toId) && !relevant.has(relation.toId)) return [];
4010
- const other = cast.find((candidate) => candidate.character.id === relation.toId);
4011
- return other === void 0 || other.key === member.key ? [] : [{
4012
- name: referent(other.character),
4013
- label: relation.label,
4014
- summary: relation.summary,
4015
- present: present.has(relation.toId),
4016
- familiarity: relation.familiarity,
4017
- trust: relation.trust,
4018
- affinity: relation.affinity,
4019
- tension: relation.tension
4020
- }];
4021
- });
4022
- }
4023
- reactions(state) {
4024
- const first = state.first;
4025
- return (first?.outcomes ?? []).flatMap((outcome) => {
4026
- const report = first?.reports.find((candidate) => candidate.character === outcome.character);
4027
- return report === void 0 ? [] : [{
4028
- character: report.character,
4029
- name: report.name,
4030
- intent: report.intent,
4031
- ...report.utterance === void 0 ? {} : { utterance: report.utterance },
4032
- result: outcome.result,
4033
- summary: outcome.summary
4034
- }];
4035
- });
4036
- }
4037
- /** The final decision for each character of the round: the retry's replaces the first attempt's. */
4038
- /** The player's character is never asked to act, so what the game master decided it did stands in for its report. */
4039
- playerReport(state, outcome) {
4040
- const member = state.cast.find((candidate) => candidate.key === outcome.character && candidate.character.control === "player");
4041
- return member === void 0 ? void 0 : {
4042
- character: member.key,
4043
- name: member.character.name,
4044
- intent: outcome.summary,
4045
- commitment: "high"
4046
- };
4047
- }
4048
- decisions(state) {
4049
- const decided = /* @__PURE__ */ new Map();
4050
- for (const attempt of [state.first, state.second]) for (const outcome of attempt?.outcomes ?? []) {
4051
- const report = attempt?.reports.find((candidate) => candidate.character === outcome.character) ?? this.playerReport(state, outcome);
4052
- if (report !== void 0) decided.set(outcome.character, {
4053
- outcome,
4054
- report
4055
- });
4056
- }
4057
- return decided;
4058
- }
4059
4173
  finishRound(owner, state) {
4060
4174
  const store = this.storeOf(owner);
4061
- const decided = this.decisions(state);
4175
+ const decided = decisions(state);
4062
4176
  const limit = store.settings().maxRounds;
4063
4177
  const round = state.rounds + 1;
4064
4178
  const checked = new Map([...decided.values()].flatMap(({ outcome }) => outcome.moveTo === void 0 ? [] : [[outcome.character, store.checkMove(outcome.character, outcome.moveTo)]]));
@@ -4286,6 +4400,11 @@ var TurnEngine = class {
4286
4400
  async deliver(owner, state, segments, silent, run) {
4287
4401
  const { narrationChecker } = this.boundaries();
4288
4402
  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)];
4403
+ const wording = wrongLanguage(this.storeOf(owner).settings().prompts.language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") });
4404
+ if (problems.length === 0 && wording !== void 0 && !silent && state.refused < MAX_REFUSALS) {
4405
+ state.refused += 1;
4406
+ throw new Error(`the output is not acceptable: ${wording}. Deliver it again with the narration corrected; utterances may not be touched`);
4407
+ }
4289
4408
  let output;
4290
4409
  if (problems.length === 0) output = {
4291
4410
  segments: asSpoken(segments, state.utterances),
@@ -4314,18 +4433,6 @@ var TurnEngine = class {
4314
4433
  return output;
4315
4434
  }
4316
4435
  };
4317
- /** The words as the character said them, whatever quotes the game master put around them. */
4318
- function asSpoken(segments, spoken) {
4319
- const left = [...spoken];
4320
- return segments.map((segment) => {
4321
- if (segment.type !== "utterance") return segment;
4322
- const at = left.findIndex((said) => said.character === segment.character && sameWords(said.text, segment.text));
4323
- return at === -1 ? segment : {
4324
- ...segment,
4325
- text: left.splice(at, 1)[0].text
4326
- };
4327
- });
4328
- }
4329
4436
  //#endregion
4330
4437
  //#region src/host/images/jobs.ts
4331
4438
  /** The same service, whose requests stand where the job's do unless a call says otherwise. */
@@ -4595,6 +4702,7 @@ function apply(ctx) {
4595
4702
  ctx.effect(() => ctx.roleplayOrchestration.replace({ committer: recordKeeper({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: record keeper");
4596
4703
  ctx.effect(() => ctx.roleplayOrchestration.replace({ judge: triggerJudge({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: trigger judge");
4597
4704
  ctx.effect(() => ctx.roleplayOrchestration.replace({ strategist: factionStrategist({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: faction strategist");
4705
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ reflector: memoryReflector({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: reflection");
4598
4706
  ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: world author");
4599
4707
  ctx.effect(() => ctx.roleplayOrchestration.replace({ suggester: suggestionWriter({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: suggestions");
4600
4708
  ctx.effect(() => ctx.roleplayState.bind((agentSessionId) => {
@@ -4648,6 +4756,14 @@ function apply(ctx) {
4648
4756
  }
4649
4757
  })].sort((a, b) => Number(b.name === PREVIEW_TOOL) - Number(a.name === PREVIEW_TOOL));
4650
4758
  for (const tool of tools) ctx.tools.register(tool);
4759
+ ctx.effect(() => {
4760
+ ctx.roleplayOrchestration.reflect = (chat) => engine.reflect(chat);
4761
+ ctx.roleplayOrchestration.reflecting = (chat) => engine.reflecting(chat);
4762
+ return () => {
4763
+ ctx.roleplayOrchestration.reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
4764
+ ctx.roleplayOrchestration.reflecting = () => false;
4765
+ };
4766
+ }, "roleplay: reflection control");
4651
4767
  ctx.effect(() => {
4652
4768
  ctx.roleplayOrchestration.settle = (chat) => engine.idle(chat);
4653
4769
  return () => {