@dsh-agentic-roleplay/core 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  3. package/lib/authoring.js +469 -17
  4. package/lib/client.js +3013 -607
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +2 -3
  7. package/lib/{activity-BbqFG9-3.js → deliver--uMhC6oO.js} +741 -55
  8. package/lib/{documents-ZVoUTnD2.js → documents-7GMc5NnW.js} +108 -5
  9. package/lib/{gallery-KGCdeCnM.js → gallery-DUeBMHQX.js} +2 -2
  10. package/lib/{generator-NYnNdpWb.js → generator-HPifO3Kk.js} +125 -20
  11. package/lib/images.js +3 -3
  12. package/lib/index.js +865 -15
  13. package/lib/{narration-DcnCqA1l.js → narration-CKZTk5UE.js} +19 -4
  14. package/lib/orchestration.js +373 -207
  15. package/lib/packs-alJTiDM2.js +1336 -0
  16. package/lib/{presenter-agent-7j1c7QEz.js → presenter-agent-PX1WVaJB.js} +4 -4
  17. package/package.json +5 -3
  18. package/packs/scene/map.html +12 -0
  19. package/packs/scene/map.js +55 -0
  20. package/packs/scene/pack.json +11 -0
  21. package/packs/scene/strip.html +11 -0
  22. package/packs/scene/strip.js +26 -0
  23. package/packs/scene/style.css +16 -0
  24. package/prompts/en/roleplay/ask-answerer.md +3 -0
  25. package/prompts/en/roleplay/ask-question.md +2 -0
  26. package/prompts/en/roleplay/character-decide.md +1 -1
  27. package/prompts/en/roleplay/character-lookup.md +1 -1
  28. package/prompts/en/roleplay/game-master.md +5 -1
  29. package/prompts/en/roleplay/ooc-empty.md +1 -1
  30. package/prompts/en/roleplay/reflection.md +9 -0
  31. package/prompts/en/world/procedure.md +1 -1
  32. package/prompts/en/world/welcome.md +1 -1
  33. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  34. package/prompts/zh/roleplay/ask-question.md +2 -0
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-lookup.md +1 -1
  37. package/prompts/zh/roleplay/game-master.md +5 -1
  38. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/world/procedure.md +1 -1
  41. package/prompts/zh/world/welcome.md +1 -1
  42. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  43. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  44. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  45. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  46. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  47. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  48. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  49. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  50. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  51. package/lib/access-C1nFQiyT.js +0 -12
  52. package/lib/worlds-DYgjdH8O.js +0 -504
@@ -1,12 +1,11 @@
1
- import { n as roleplaySessionOf, t as chatSessionId } from "./chat-AKrVcWIC.js";
2
- import { D as INTENT_STATUSES, i as parsePlotsFile, t as API_PREFIX, y as shippedText } from "./worlds-DYgjdH8O.js";
3
- import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-DcnCqA1l.js";
1
+ import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
+ import { F as shippedText, W as INTENT_STATUSES, _ as API_PREFIX, b as parsePlotsFile, z as ReflectionRefusedError } from "./packs-alJTiDM2.js";
3
+ import { B as skipTime, D as observeSurroundings, E as observeAsPlayer, F as beginTurn, G as RESULTS, H as referent, I as describeTime, 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, _ 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--uMhC6oO.js";
4
+ import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-CKZTk5UE.js";
4
5
  import "./src-CWTNeL6Y.js";
5
- import { A as runChild, D as childSampling, E as childModel, T as uniqueKey, k as childTrace, o as addToLibrary, w as slug } from "./generator-NYnNdpWb.js";
6
- import { C as describeWhen, D as zoneOf, E as skipTime, S as describeTime, T as readTime, _ as Timelines, b as ClockError, d as pacingAdvice, f as plotAuthorNeeded, h as updatePlotProgress, i as clearNotes, l as addSessionPlot, n as recordActivity, o as putNote, r as addToNote, s as readNotes, u as describePacingAdvice, w as endRound, x as beginTurn, y as sameWords } from "./activity-BbqFG9-3.js";
7
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-KGCdeCnM.js";
8
- import { t as promptFor } from "./access-C1nFQiyT.js";
9
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-7j1c7QEz.js";
6
+ 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";
7
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DUeBMHQX.js";
8
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PX1WVaJB.js";
10
9
  import { join } from "node:path";
11
10
  import { existsSync } from "node:fs";
12
11
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -29,7 +28,7 @@ const VERIFY_SECTIONS = [
29
28
  "engagements"
30
29
  ];
31
30
  const label = (round) => `turn ${round.turn}, round ${round.round}`;
32
- function describeRound(round) {
31
+ function describeRound(round, known) {
33
32
  return [
34
33
  `## ${label(round)}`,
35
34
  round.offstage === true ? `Off stage (away from the player's character; only the characters named here perceive it, and only those who were together perceive each other): ${round.situation}` : `The moment (includes what the player's character did or said): ${round.situation}`,
@@ -37,7 +36,7 @@ function describeRound(round) {
37
36
  ...round.time === void 0 ? [] : [`When: ${describeInstant(round.time.from, round.time.zone)} (${dayPart(localTime(round.time.from, round.time.zone).minuteOfDay)})${round.time.to > round.time.from ? `; the round took ${describeDuration(round.time.to - round.time.from)}` : ""}`],
38
37
  "What each character did, and what became of it:",
39
38
  ...round.entries.map((entry) => [
40
- entry.forced === true ? `- ${entry.character} (${entry.name}): decreed, not chosen: ${entry.result}: ${entry.summary}` : entry.player === true ? `- ${entry.character} (${entry.name}, the player's character): ${entry.result}: ${entry.summary}` : `- ${entry.character} (${entry.name}): intended "${entry.intent}" [commitment: ${entry.commitment}]; ${entry.result}: ${entry.summary}`,
39
+ entry.forced === true ? `- ${entry.character} (${known.get(entry.character) ?? entry.name}): decreed, not chosen: ${entry.result}: ${entry.summary}` : entry.player === true ? `- ${entry.character} (${known.get(entry.character) ?? entry.name}, the player's character): ${entry.result}: ${entry.summary}` : `- ${entry.character} (${known.get(entry.character) ?? entry.name}): intended "${entry.intent}" [commitment: ${entry.commitment}]; ${entry.result}: ${entry.summary}`,
41
40
  entry.utterance === void 0 ? "" : ` said${entry.spoken ? "" : " (but was prevented from saying)"}: "${entry.utterance}"`,
42
41
  entry.publicState === void 0 ? "" : ` the game master says anyone present can now see: ${entry.publicState}`,
43
42
  entry.variables === void 0 ? "" : ` the game master changed what is tracked: ${entry.variables.map((change) => `${change.subject}'s ${change.name} ${change.from} -> ${change.to}`).join("; ")}`,
@@ -56,6 +55,7 @@ function describePrompt(job, memory) {
56
55
  const first = job.rounds[0];
57
56
  const records = job.store.story.records({ timeZone: zoneOf(job.store.settings().clock) });
58
57
  const own = job.store.story.records({ rounds }).events;
58
+ const known = new Map(job.store.cast().map((member) => [member.key, referent(member.character)]));
59
59
  const before = records.events.filter((event) => event.turn < first.turn || event.turn === first.turn && event.round < first.round).slice(-6);
60
60
  return [
61
61
  memory.flaky ? "Perception in this chat: characters do not perceive perfectly. Mark a perception partial only when the character could take in just part of it (overheard, glimpsed), and mistaken only when the material shows it taking in something false; in both cases put the character's own version in content. Otherwise it is accurate and content is left out." : "Perception in this chat: every character perceives exactly what happened. Leave accuracy and content out.",
@@ -64,9 +64,9 @@ function describePrompt(job, memory) {
64
64
  job.rounds.length > 1 ? `${job.rounds.length} rounds are due for records: write all of them, oldest first.` : `${label(first)} is due for records.`,
65
65
  ...job.focus === void 0 || job.focus.length === 0 ? [] : ["", `The game master says this is worth keeping: ${job.focus.join("; ")}`],
66
66
  "",
67
- ...job.rounds.flatMap(describeRound),
67
+ ...job.rounds.flatMap((round) => describeRound(round, known)),
68
68
  "## State of the characters now",
69
- ...records.characters.map((entry) => `- ${entry.character} (${entry.name}, ${entry.controlled_by}): public: ${entry.public_state || "-"}; inner: ${entry.inner_state || "-"}; doing: ${entry.activity || "-"}${entry.location === null ? "" : `; in: ${entry.location}${entry.position === "" ? "" : ` (${entry.position})`}`}`),
69
+ ...records.characters.map((entry) => `- ${entry.character} (${known.get(entry.character) ?? entry.name}, ${entry.controlled_by}): public: ${entry.public_state || "-"}; inner: ${entry.inner_state || "-"}; doing: ${entry.activity || "-"}${entry.location === null ? "" : `; in: ${entry.location}${entry.position === "" ? "" : ` (${entry.position})`}`}`),
70
70
  "",
71
71
  "## Recorded before these rounds (do not repeat)",
72
72
  ...before.length === 0 ? ["- nothing"] : before.map((event) => `- [turn ${event.turn}] ${event.text}`),
@@ -240,7 +240,7 @@ function promptOf(job) {
240
240
  const place = player?.place?.location.name;
241
241
  return [
242
242
  `Write exactly ${job.count} suggestion${job.count === 1 ? "" : "s"}.`,
243
- `The player plays ${player?.character.name ?? "their character"}${place === void 0 ? "" : `, who is at ${place}`}.`,
243
+ `The player plays ${player === void 0 ? "their character" : referent(player.character)}${place === void 0 ? "" : `, who is at ${place}`}.`,
244
244
  "",
245
245
  "What the player has just read:",
246
246
  readingOf(job)
@@ -255,7 +255,7 @@ function suggestionWriter(deps) {
255
255
  parent,
256
256
  signal,
257
257
  reasoningEffort: job.store.settings().reasoning.children,
258
- sampling: childSampling(job.store.settings(), "suggestions"),
258
+ sampling: childSampling(job.store.settings(), "suggestions", estimateAnswer(Array.from({ length: job.count }, () => 200), job.store.settings().prompts.language)),
259
259
  ...childModel(job.store.settings(), "suggestions"),
260
260
  trace: childTrace(job.store, "suggestions", "suggestions"),
261
261
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
@@ -912,20 +912,23 @@ function fireTriggers(session, input) {
912
912
  for (const failure of run.failed) problem(`the trigger "${failure.trigger.key}" could not fire and is given up: ${failure.problem}`);
913
913
  const names = new Map(session.characters.list().map((character) => [character.id, character.name]));
914
914
  const fresh = session.triggers.notes({ status: "pending" }).filter((note) => note.id > before);
915
+ const told = new Map(deliverNow(session, fresh, {
916
+ now,
917
+ zone
918
+ }).map((entry) => [entry.id, entry.text]));
915
919
  return { fired: run.fired.map((fired) => ({
916
920
  name: fired.trigger.name,
917
921
  events: fired.events,
918
- cues: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "cue").map((note) => ({
922
+ cues: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "cue" && told.has(note.id)).map((note) => ({
919
923
  names: note.characterIds.flatMap((id) => names.get(id) ?? []),
920
- text: note.text
924
+ text: told.get(note.id)
921
925
  })),
922
- beats: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "beat").map((note) => ({
926
+ beats: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "beat" && told.has(note.id)).map((note) => ({
923
927
  id: note.id,
924
- text: note.text
928
+ text: told.get(note.id)
925
929
  }))
926
930
  })) };
927
931
  }
928
- /** The beats still to weave in, the cues of a character, and what is done with them. */
929
932
  /** When something is to happen, as it is told: the date and how far off it is. */
930
933
  function whenText(at, clock) {
931
934
  if (at === void 0) return void 0;
@@ -939,6 +942,7 @@ function whoKnows(session, announcement) {
939
942
  }
940
943
  /** At most this many announcements are told to one character at once: soonest first. */
941
944
  const MAX_UPCOMING_FOR_CHARACTER = 3;
945
+ /** 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. */
942
946
  function noteStore(session, settings, clock) {
943
947
  return {
944
948
  upcoming: (turn) => {
@@ -962,13 +966,10 @@ function noteStore(session, settings, clock) {
962
966
  };
963
967
  });
964
968
  },
965
- pendingBeats: () => session.triggers.notes({
969
+ pendingBeats: () => deliverNow(session, session.triggers.notes({
966
970
  status: "pending",
967
971
  kind: "beat"
968
- }).map((note) => ({
969
- id: note.id,
970
- text: note.text
971
- })),
972
+ }), clock(session.metadata.get().turns + 1)),
972
973
  resolveBeats: (ids) => {
973
974
  const pending = new Set(session.triggers.notes({
974
975
  status: "pending",
@@ -980,13 +981,10 @@ function noteStore(session, settings, clock) {
980
981
  for (const id of ids) session.triggers.resolveNote(id, "done");
981
982
  });
982
983
  },
983
- cuesFor: (characterId) => session.triggers.notes({
984
+ cuesFor: (characterId) => deliverNow(session, session.triggers.notes({
984
985
  status: "pending",
985
986
  kind: "cue"
986
- }).filter((note) => note.characterIds.includes(characterId)).map((note) => ({
987
- id: note.id,
988
- text: note.text
989
- })),
987
+ }).filter((note) => note.characterIds.includes(characterId)), clock(session.metadata.get().turns + 1)),
990
988
  doneCues: (ids) => {
991
989
  session.transaction(() => {
992
990
  for (const id of ids) session.triggers.resolveNote(id, "done");
@@ -1002,35 +1000,6 @@ function noteStore(session, settings, clock) {
1002
1000
  };
1003
1001
  }
1004
1002
  //#endregion
1005
- //#region src/host/orchestration/observation.ts
1006
- /** 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. */
1007
- function observeSurroundings(session, characterId, turn) {
1008
- const placement = session.placements.get("character", characterId);
1009
- if (placement !== void 0) {
1010
- session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1011
- for (const exit of session.locations.exitsFrom(placement.locationId)) {
1012
- session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1013
- session.knowledge.learn(characterId, "location", exit.toId, turn);
1014
- }
1015
- for (const { item } of session.items.contents({
1016
- kind: "location",
1017
- id: placement.locationId
1018
- })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1019
- }
1020
- for (const { item } of session.items.contents({
1021
- kind: "character",
1022
- id: characterId
1023
- })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1024
- }
1025
- /**
1026
- * 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
1027
- * how it comes to know the way back from where it went.
1028
- */
1029
- function observeAsPlayer(session, turn) {
1030
- const player = session.characters.list().find((character) => character.control === "player");
1031
- if (player !== void 0) observeSurroundings(session, player.id, turn);
1032
- }
1033
- //#endregion
1034
1003
  //#region src/host/clock/agenda.ts
1035
1004
  const CURSOR = "agenda.cursor";
1036
1005
  const ASKED = "agenda.asked";
@@ -1374,11 +1343,11 @@ function knowledgeOf(session, characterId, turn, visibleCharacters) {
1374
1343
  for (const otherId of visibleCharacters ?? (placement === void 0 ? [] : session.placements.at(placement.locationId, "character").map((other) => other.entityId))) if (otherId !== characterId && session.relationships.get(characterId, otherId) === void 0) session.relationships.upsert(characterId, otherId, { label: "acquaintance" }, turn);
1375
1344
  const locations = session.knowledge.list(characterId, "location").flatMap((entry) => {
1376
1345
  const place = session.locations.get(entry.subjectId);
1377
- return place === void 0 ? [] : [`${place.name} (${locationKey(place)})`];
1346
+ return place === void 0 ? [] : [place.name];
1378
1347
  });
1379
1348
  const items = session.knowledge.list(characterId, "item").flatMap((entry) => {
1380
1349
  const item = session.items.get(entry.subjectId);
1381
- return item === void 0 ? [] : [`${item.name} (${itemKey(item)})`];
1350
+ return item === void 0 ? [] : [item.name];
1382
1351
  });
1383
1352
  const allExits = session.locations.allExits();
1384
1353
  const routes = session.knowledge.list(characterId, "exit").flatMap((entry) => {
@@ -1390,11 +1359,11 @@ function knowledgeOf(session, characterId, turn, visibleCharacters) {
1390
1359
  return {
1391
1360
  characters: session.relationships.from(characterId).flatMap((relation) => {
1392
1361
  const character = session.characters.get(relation.toId);
1393
- return character === void 0 ? [] : [`${character.name} (${keyOfCharacter(character)})`];
1362
+ return character === void 0 ? [] : [character.name];
1394
1363
  }),
1395
1364
  factions: session.factionRelationships.from("character", characterId).filter((relation) => relation.toKind === "faction").flatMap((relation) => {
1396
1365
  const faction = session.factions.get(relation.toId);
1397
- return faction === void 0 ? [] : [`${faction.name} (${faction.sourceId ?? faction.id})`];
1366
+ return faction === void 0 ? [] : [faction.name];
1398
1367
  }),
1399
1368
  locations,
1400
1369
  items,
@@ -1612,8 +1581,9 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
1612
1581
  addNote: (kind, turn, lines) => {
1613
1582
  addToNote(session, kind, turn, lines);
1614
1583
  },
1615
- recordActivity: (entry) => {
1616
- recordActivity(session, entry);
1584
+ recordActivity: (entry, detail) => {
1585
+ if (detail !== void 0 && entry.run !== void 0) keepRunDetail(folder, entry.run, detail);
1586
+ forgetRunDetails(folder, recordActivity(session, entry));
1617
1587
  },
1618
1588
  notes: () => readNotes(session),
1619
1589
  clearNotes: () => {
@@ -1661,13 +1631,18 @@ function storesOf(state, sessionsDir, problem = () => void 0, queryVector = () =
1661
1631
  }
1662
1632
  //#endregion
1663
1633
  //#region src/shared/ooc.ts
1664
- /** What the player writes to give the game master an out-of-character command: a turn of its own, never mixed with an action of the character. */
1665
- const OOC_COMMAND = /^\s*\/ooc(?=\s|$)\s*([\s\S]*)$/i;
1666
- /** The command in a player's message, or nothing when the message is an ordinary action. The command may be empty. */
1634
+ /** What the player writes to speak to the game master as the author of the story: a command (`/ooc`) or a question (`/ask`), a turn of its own, never mixed with an action of the character. */
1635
+ const OOC_COMMAND = /^\s*\/(ooc|ask)(?=\s|$)\s*([\s\S]*)$/i;
1636
+ /** The command or question in a player's message, or nothing when the message is an ordinary action. The request may be empty. */
1667
1637
  function parseOoc(text) {
1668
1638
  const match = OOC_COMMAND.exec(text);
1669
- return match === null ? void 0 : { request: (match[1] ?? "").trim() };
1639
+ return match === null ? void 0 : {
1640
+ request: (match[2] ?? "").trim(),
1641
+ question: match[1].toLowerCase() === "ask"
1642
+ };
1670
1643
  }
1644
+ /** The longest answer to an out-of-character question. */
1645
+ const MAX_OOC_ANSWER = 1200;
1671
1646
  //#endregion
1672
1647
  //#region src/host/orchestration/hooks.ts
1673
1648
  const notice = (text) => createUserMessage({
@@ -1749,7 +1724,7 @@ function installHooks(ctx, deps) {
1749
1724
  turn: payload.turn,
1750
1725
  cast
1751
1726
  }) : { ok: true };
1752
- if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request);
1727
+ if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
1753
1728
  else if (ooc === void 0) engine.expectJudgement(owner);
1754
1729
  const queryVector = await store.queryVector(ooc?.request ?? text);
1755
1730
  store.clearNotes();
@@ -1785,10 +1760,10 @@ function installHooks(ctx, deps) {
1785
1760
  else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
1786
1761
  const rules = store.rules();
1787
1762
  if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
1788
- if (ooc !== void 0 && ooc.request !== "") lines.push(store.text("roleplay/ooc-command", { request: ooc.request }));
1763
+ if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
1789
1764
  if (ooc !== void 0 && ooc.request === "") {
1790
1765
  engine.skip(owner);
1791
- lines.push(store.text("roleplay/ooc-empty"));
1766
+ lines.push(store.text("roleplay/ooc-empty", { command: ooc.question ? "/ask" : "/ooc" }));
1792
1767
  }
1793
1768
  if (!verdict.ok) {
1794
1769
  engine.skip(owner);
@@ -1816,107 +1791,6 @@ function currentTurn(agent) {
1816
1791
  return 0;
1817
1792
  }
1818
1793
  //#endregion
1819
- //#region src/host/orchestration/protocol.ts
1820
- const COMMITMENTS = [
1821
- "low",
1822
- "medium",
1823
- "high"
1824
- ];
1825
- const RESULTS = [
1826
- "succeeded",
1827
- "partial",
1828
- "failed"
1829
- ];
1830
- /** What a character is asked to produce; the sub-agent runtime enforces it. */
1831
- const CHARACTER_ACTION_SCHEMA = {
1832
- type: "object",
1833
- properties: {
1834
- intent: {
1835
- type: "string",
1836
- description: "What the character does, or tries to do, now, as an action in one or two sentences, without any speech."
1837
- },
1838
- utterance: {
1839
- type: "string",
1840
- description: "What the character says aloud, word for word and in its own voice, exactly as it will be shown. Leave out when it says nothing."
1841
- },
1842
- commitment: {
1843
- type: "string",
1844
- enum: [...COMMITMENTS],
1845
- description: "How hard the character will keep trying if this does not work out: low gives up at once, high persists."
1846
- }
1847
- },
1848
- required: ["intent", "commitment"],
1849
- additionalProperties: false
1850
- };
1851
- /** The schema for a character acting away from the player: the same answer, which also says in a line what happened, so no second request is needed. */
1852
- const AWAY_ACTION_SCHEMA = {
1853
- ...CHARACTER_ACTION_SCHEMA,
1854
- properties: {
1855
- ...CHARACTER_ACTION_SCHEMA.properties,
1856
- account: {
1857
- type: "string",
1858
- description: "One sentence, in the third person and the past tense, of what came of this, as someone who only saw it from outside would tell it afterwards: no thoughts, no secrets."
1859
- }
1860
- },
1861
- required: [
1862
- "intent",
1863
- "commitment",
1864
- "account"
1865
- ]
1866
- };
1867
- const MAX_ACCOUNT = 300;
1868
- /** @throws {Error} when the value is not a character action. */
1869
- const QUOTE_PAIRS = [
1870
- ["\"", "\""],
1871
- ["“", "”"],
1872
- ["「", "」"],
1873
- ["『", "』"],
1874
- ["«", "»"],
1875
- ["‘", "’"]
1876
- ];
1877
- /** Words said aloud, without the quotation marks a model puts around them: the output puts its own. */
1878
- function unquoted(text) {
1879
- let words = text.trim();
1880
- for (let again = true; again;) {
1881
- again = false;
1882
- for (const [open, close] of QUOTE_PAIRS) if (words.length >= 2 && words.startsWith(open) && words.endsWith(close) && !words.slice(open.length, -close.length).includes(close)) {
1883
- words = words.slice(open.length, words.length - close.length).trim();
1884
- again = true;
1885
- }
1886
- }
1887
- return words;
1888
- }
1889
- const LEAKED_FIELD = /<\/?(?:intent|parameter(?:=\w+)?)>/g;
1890
- /** A model that writes the markup of its call into a field puts the next field's text inside this one. */
1891
- function splitLeakedFields(intent) {
1892
- const at = intent.search(/<parameter=utterance>/);
1893
- if (at === -1) return { intent: intent.replace(LEAKED_FIELD, " ") };
1894
- const spoken = intent.slice(at).replace(LEAKED_FIELD, " ").trim();
1895
- return {
1896
- intent: intent.slice(0, at).replace(LEAKED_FIELD, " "),
1897
- ...spoken === "" ? {} : { utterance: spoken }
1898
- };
1899
- }
1900
- function parseCharacterAction(value) {
1901
- if (typeof value !== "object" || value === null) throw new Error("the character did not answer with an object");
1902
- const { intent: rawIntent, utterance: rawUtterance, commitment, account } = value;
1903
- const { intent, utterance } = typeof rawIntent === "string" && rawUtterance === void 0 ? splitLeakedFields(rawIntent) : {
1904
- intent: rawIntent,
1905
- utterance: rawUtterance
1906
- };
1907
- if (typeof intent !== "string" || intent.trim() === "") throw new Error("the character gave no intent");
1908
- if (!COMMITMENTS.includes(commitment)) throw new Error(`the character gave an unknown commitment "${String(commitment)}"`);
1909
- if (utterance !== void 0 && typeof utterance !== "string") throw new Error("the character's utterance is not text");
1910
- const spoken = utterance === void 0 ? void 0 : unquoted(utterance);
1911
- const told = typeof account === "string" ? account.trim().slice(0, MAX_ACCOUNT) : "";
1912
- return {
1913
- intent: intent.trim(),
1914
- ...spoken === void 0 || spoken === "" ? {} : { utterance: spoken },
1915
- commitment,
1916
- ...told === "" ? {} : { account: told }
1917
- };
1918
- }
1919
- //#endregion
1920
1794
  //#region src/host/orchestration/character-runner.ts
1921
1795
  /**
1922
1796
  * Runs each character as a one-shot child of the game master. It is the character and nothing
@@ -1933,19 +1807,64 @@ function characterRunner(deps) {
1933
1807
  policy: deps.store.settings().memory,
1934
1808
  queryVector: deps.store.queryVector
1935
1809
  }), request.member.character.id) : [];
1936
- return parseCharacterAction(await runChild({
1810
+ const settings = deps.store.settings();
1811
+ const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
1812
+ const result = await runChild({
1937
1813
  parent: deps.parent,
1938
1814
  signal,
1939
- sampling: childSampling(deps.store.settings(), "characters"),
1940
- ...childModel(deps.store.settings(), "characters"),
1941
- trace: childTrace(deps.store, "characters", request.member.character.name),
1815
+ sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
1816
+ ...childModel(settings, "characters", named),
1817
+ trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named),
1942
1818
  reasoningEffort: deps.store.settings().reasoning.children,
1943
1819
  persona: brief.persona,
1944
1820
  prompt: brief.prompt,
1945
1821
  tools,
1946
1822
  maxCalls: deps.store.settings().memory.lookupCalls,
1947
- result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA
1948
- }));
1823
+ result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
1824
+ unenforced: ["thought"]
1825
+ });
1826
+ return parseCharacterAction(result);
1827
+ };
1828
+ }
1829
+ /** What the character was reminded of and why, for the run's record, when the recall said why. */
1830
+ function recalledOf(request) {
1831
+ const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
1832
+ return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
1833
+ clarity,
1834
+ turn,
1835
+ text,
1836
+ why
1837
+ })) };
1838
+ }
1839
+ const ANSWER_SCHEMA = {
1840
+ type: "object",
1841
+ properties: { answer: {
1842
+ type: "string",
1843
+ description: "The answer to the player, in plain words, in a few sentences."
1844
+ } },
1845
+ required: ["answer"],
1846
+ additionalProperties: false
1847
+ };
1848
+ /**
1849
+ * Answers a player's question as an agent that has only what the player's character is given when it acts: the character sheet is left out and nothing the
1850
+ * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
1851
+ */
1852
+ function answerRunner(deps) {
1853
+ return async (request, signal) => {
1854
+ const brief = deps.boundaries().characterContext.brief(request);
1855
+ return (await runChild({
1856
+ parent: deps.parent,
1857
+ signal,
1858
+ sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
1859
+ ...childModel(deps.store.settings(), "records"),
1860
+ trace: childTrace(deps.store, "records", "answer to the player"),
1861
+ reasoningEffort: deps.store.settings().reasoning.children,
1862
+ persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
1863
+ prompt: brief.prompt,
1864
+ tools: [],
1865
+ maxCalls: 3,
1866
+ result: ANSWER_SCHEMA
1867
+ })).answer;
1949
1868
  };
1950
1869
  }
1951
1870
  //#endregion
@@ -2108,6 +2027,7 @@ const INTRODUCE_TOOL = "introduce_thing";
2108
2027
  const TIME_TOOL = "advance_time";
2109
2028
  const PREVIEW_TOOL = "preview_scene";
2110
2029
  const RULING_TOOL = "ooc_ruling";
2030
+ const ANSWER_TOOL = "ooc_answer";
2111
2031
  const JUDGE_TOOL = "judge_action";
2112
2032
  const PLOT_TOOL = "record_plot_progress";
2113
2033
  const AUTHOR_PLOT_TOOL = "author_plot";
@@ -2119,7 +2039,7 @@ function failures(list) {
2119
2039
  return list.length === 0 ? [] : [
2120
2040
  "",
2121
2041
  "Could not act:",
2122
- ...list.map((failure) => `- ${failure.character} (${failure.name}): ${failure.reason}`)
2042
+ ...list.map((failure) => failure.technical === true ? `- ${failure.character} (${failure.name}): no decision came back. That is a fault of the system, not something that happened in the story: nothing is recorded for ${failure.name} this round, so write nothing for them and say nothing about why` : `- ${failure.character} (${failure.name}): ${failure.reason}`)
2123
2043
  ];
2124
2044
  }
2125
2045
  function renderAttempt(attempt) {
@@ -2203,16 +2123,16 @@ function createTools$1(deps) {
2203
2123
  name: ACTIVATE_TOOL,
2204
2124
  description: "Let the characters act: one round of the turn. Each character asked is asked, separately and at the same time, what it intends to do and say in the situation you describe and how committed it is. Call it after reading what the player did, and again for a later round only when the story genuinely needs the characters to react to what just happened; the number of rounds for one player message is limited.",
2205
2125
  parameters: {
2206
- situation: {
2207
- type: "string",
2208
- required: true,
2209
- description: "An objective description of the moment: in the first round what the player's character just did or said; in a later round what is happening now, following from the rounds before (they are told those too). Every character is told this and nothing more, so leave out anyone's private thoughts."
2210
- },
2211
2126
  characters: {
2212
2127
  type: "array",
2213
2128
  required: true,
2214
2129
  items: { type: "string" },
2215
2130
  description: "Keys of the characters to ask, chosen by you from the scene (where each is, what each is doing). Ask only those the moment reaches: those in the same place, and those elsewhere who can plainly see, hear or are summoned; a character elsewhere perceives nothing by itself. Never the whole cast. In a later round ask only those the moment calls for."
2131
+ },
2132
+ situation: {
2133
+ type: "string",
2134
+ required: true,
2135
+ description: "An objective description of the moment: in the first round what the player's character just did or said; in a later round what is happening now, following from the rounds before (they are told those too). Every character is told this and nothing more, so leave out anyone's private thoughts."
2216
2136
  }
2217
2137
  },
2218
2138
  output: {
@@ -2241,10 +2161,6 @@ function createTools$1(deps) {
2241
2161
  name: RESOLVE_TOOL,
2242
2162
  description: "Decide what actually happens to each character that acted in the current round, from their intents and the scene only. Intents can conflict; settle them consistently. A character whose intent fails and who was highly committed gets one more chance, and you resolve that attempt too. The player's character is not asked to act, but you may include an outcome for it (its key is in the scene) when what the player did moves it somewhere or has it handle things; when nobody else needs to react (the player just walks somewhere, picks something up), call this with only that outcome, without activate_characters. When nobody retries, the round is recorded and you decide whether another round is needed or the turn goes back to the player.",
2243
2163
  parameters: {
2244
- elapsed_seconds: {
2245
- type: "integer",
2246
- description: "How long this round took in the story, in seconds:: a few seconds for a remark, a minute or two for a conversation, longer for work or a journey. Left out, the chat's default applies. Not when the story's time follows the wall clock."
2247
- },
2248
2164
  outcomes: {
2249
2165
  type: "array",
2250
2166
  required: true,
@@ -2391,6 +2307,10 @@ function createTools$1(deps) {
2391
2307
  }
2392
2308
  }
2393
2309
  }
2310
+ },
2311
+ elapsed_seconds: {
2312
+ type: "integer",
2313
+ description: "How long this round took in the story, in seconds:: a few seconds for a remark, a minute or two for a conversation, longer for work or a journey. Left out, the chat's default applies. Not when the story's time follows the wall clock."
2394
2314
  }
2395
2315
  },
2396
2316
  output: {
@@ -2695,6 +2615,11 @@ function createTools$1(deps) {
2695
2615
  name: TIME_TOOL,
2696
2616
  description: "Skip ahead in the story's time, between rounds: the player's character sleeps till morning, waits, or travels for days. Say either how long (by_minutes) or until when (until_time, and days_later for a later day). Time does not otherwise pass faster than the rounds take; use this only for a stretch that is summarised rather than played. Nothing else changes: if the skip changes what characters are doing or where they are, run a round for them afterwards. Not available when the story's time follows the wall clock.",
2697
2617
  parameters: {
2618
+ reason: {
2619
+ type: "string",
2620
+ required: true,
2621
+ description: "What happens in the time that passes, in a sentence (\"they sleep\", \"the ferry crosses\")."
2622
+ },
2698
2623
  by_minutes: {
2699
2624
  type: "integer",
2700
2625
  description: "How many minutes to skip."
@@ -2706,11 +2631,6 @@ function createTools$1(deps) {
2706
2631
  days_later: {
2707
2632
  type: "integer",
2708
2633
  description: "With until_time: that many days after today (0 is later today, 1 is tomorrow)."
2709
- },
2710
- reason: {
2711
- type: "string",
2712
- required: true,
2713
- description: "What happens in the time that passes, in a sentence (\"they sleep\", \"the ferry crosses\")."
2714
2634
  }
2715
2635
  },
2716
2636
  output: {
@@ -2797,6 +2717,27 @@ function createTools$1(deps) {
2797
2717
  return Promise.resolve(record(deps.engine.rule(owner, args.legal, args.reason)));
2798
2718
  }
2799
2719
  });
2720
+ const answer = defineTool({
2721
+ name: ANSWER_TOOL,
2722
+ description: "Have the player's out-of-character question answered, as the very first thing of a question turn. You do not write the answer: it is written from what the player's character knows (what it remembers, knows to exist, carries and sees where it is), so that nothing hidden is given away. Nothing in the story changes, nobody is asked to act and time does not pass.",
2723
+ parameters: {},
2724
+ output: {
2725
+ schema: { type: "json" },
2726
+ render: () => [{
2727
+ type: "text",
2728
+ text: `The player is shown the answer. Now call ${NARRATE_TOOL} with no segments.`
2729
+ }]
2730
+ },
2731
+ isConcurrencySafe: () => false,
2732
+ async execute(_args, exec) {
2733
+ const { agent, owner } = ownerOf(exec.agent);
2734
+ return record(await deps.engine.answer(owner, answerRunner({
2735
+ parent: agent,
2736
+ boundaries: deps.boundaries,
2737
+ store: storeOf(owner.chat)
2738
+ }), exec.signal));
2739
+ }
2740
+ });
2800
2741
  return [
2801
2742
  defineTool({
2802
2743
  name: JUDGE_TOOL,
@@ -2807,6 +2748,10 @@ function createTools$1(deps) {
2807
2748
  required: true,
2808
2749
  description: "First, go through every rule the scene lists, one by one, in a few words each: does what the character tries need what the rule excludes? The rules are literal. Then whether it is viable here. Write \"no rules listed\" when there are none."
2809
2750
  },
2751
+ at: {
2752
+ type: "string",
2753
+ description: "The key of the place where the action happens, only when the player says it happens at a particular place (talking to the baker in the market, searching the cellar) rather than where the character is. If the character is somewhere else the action cannot work: it has to go there first. Leave it out when the action happens where the character is, and when the player is going somewhere (the journey is its own action)."
2754
+ },
2810
2755
  allowed: {
2811
2756
  type: "boolean",
2812
2757
  required: true,
@@ -2822,17 +2767,18 @@ function createTools$1(deps) {
2822
2767
  schema: { type: "json" },
2823
2768
  render: (_args, value) => [{
2824
2769
  type: "text",
2825
- text: value.allowed ? `Judged: it can work. Now call ${PREVIEW_TOOL} (when the scene asks for it) and ${ACTIVATE_TOOL}, describing only what the character does.` : `Judged: it cannot work. Play the failed attempt: ${RESOLVE_TOOL} with one outcome for the player's character (result failed, one sentence: what it does, what comes of it, why not) and nothing else, then ${NARRATE_TOOL}. Narrate what a witness would see of the attempt, never the effect the player claimed.`
2770
+ text: value.allowed ? `Judged: it can work. Now call ${PREVIEW_TOOL} (when the scene asks for it) and ${ACTIVATE_TOOL}, describing only what the character does.` : `Judged: it cannot work${value.elsewhere === true ? ` (${value.reason})` : ""}. Play the failed attempt: ${RESOLVE_TOOL} with one outcome for the player's character (result failed, one sentence: what it does, what comes of it, why not) and nothing else, then ${NARRATE_TOOL}. Narrate what a witness would see of the attempt, never the effect the player claimed.`
2826
2771
  }]
2827
2772
  },
2828
2773
  isConcurrencySafe: () => false,
2829
2774
  execute(args, exec) {
2830
2775
  const { owner } = ownerOf(exec.agent);
2831
- return Promise.resolve(record(deps.engine.judge(owner, args.allowed, args.reason)));
2776
+ return Promise.resolve(record(deps.engine.judge(owner, args.allowed, args.reason, args.at)));
2832
2777
  }
2833
2778
  }),
2834
2779
  preview,
2835
2780
  ruling,
2781
+ answer,
2836
2782
  activate,
2837
2783
  resolve,
2838
2784
  skip,
@@ -2981,6 +2927,7 @@ var AfterTurnJobs = class {
2981
2927
  consolidating = /* @__PURE__ */ new Set();
2982
2928
  strategizing = /* @__PURE__ */ new Set();
2983
2929
  judging = /* @__PURE__ */ new Set();
2930
+ reflecting = /* @__PURE__ */ new Set();
2984
2931
  constructor(deps) {
2985
2932
  this.deps = deps;
2986
2933
  }
@@ -2988,6 +2935,42 @@ var AfterTurnJobs = class {
2988
2935
  this.consolidate(owner, cancel);
2989
2936
  this.strategize(owner, cancel);
2990
2937
  this.judge(owner, cancel);
2938
+ const reason = this.reflectionDue(owner);
2939
+ if (reason !== void 0) this.reflect(owner, reason, cancel);
2940
+ }
2941
+ /** Whether a reflection is running for the chat. */
2942
+ isReflecting(chat) {
2943
+ return this.reflecting.has(chat);
2944
+ }
2945
+ /** Starts a reflection the player asked for, without waiting for it. @throws {ReflectionRefusedError} when one is already running. */
2946
+ reflectNow(owner, cancel) {
2947
+ if (this.deps.stores(owner.chat) === void 0) throw new Error(`no story for chat ${owner.chat}`);
2948
+ if (this.reflecting.has(owner.chat)) throw new ReflectionRefusedError("a reflection is already running");
2949
+ this.reflect(owner, "manual", cancel);
2950
+ }
2951
+ reflectionDue(owner) {
2952
+ const store = this.deps.stores(owner.chat);
2953
+ return store === void 0 || this.reflecting.has(owner.chat) ? void 0 : dueReflection(store, owner.turn);
2954
+ }
2955
+ /** 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. */
2956
+ reflect(owner, reason, cancel) {
2957
+ const store = this.deps.stores(owner.chat);
2958
+ if (store === void 0) return;
2959
+ this.reflecting.add(owner.chat);
2960
+ this.deps.track(owner.chat, this.deps.boundaries().reflector.reflect({
2961
+ chat: owner.chat,
2962
+ turn: owner.turn,
2963
+ store,
2964
+ reason
2965
+ }, cancel).then((report) => {
2966
+ if (report.characters.length > 0) this.deps.written(owner.chat);
2967
+ }).catch((error) => {
2968
+ if (cancel.aborted) return;
2969
+ recordFailure(store.story, messageOf(error));
2970
+ this.deps.problem(`what the characters believe was not sorted: ${messageOf(error)}`);
2971
+ }).finally(() => {
2972
+ this.reflecting.delete(owner.chat);
2973
+ }));
2991
2974
  }
2992
2975
  /** Fit what was made up into the rest of the world, when enough of it is waiting or some has waited long. */
2993
2976
  consolidate(owner, cancel) {
@@ -3048,6 +3031,54 @@ var AfterTurnJobs = class {
3048
3031
  const MAX_OBJECTIONS = 3;
3049
3032
  /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
3050
3033
  const MAX_ROUND_SECONDS = 86400;
3034
+ /**
3035
+ * 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
3036
+ * character either. When the label is exactly a character of the scene, the label is folded into the words that follow it.
3037
+ */
3038
+ function foldSpeakerLabels(segments, cast) {
3039
+ const found = (label) => {
3040
+ const wanted = label.trim().normalize("NFKC").toLowerCase();
3041
+ return wanted === "" ? void 0 : cast.find((member) => member.key.toLowerCase() === wanted || member.character.name.normalize("NFKC").toLowerCase() === wanted);
3042
+ };
3043
+ const folded = [];
3044
+ for (let index = 0; index < segments.length; index += 1) {
3045
+ const segment = segments[index];
3046
+ const next = segments[index + 1];
3047
+ const speaker = segment.type === "utterance" && (segment.character ?? "") === "" && next?.type === "utterance" && (next.character ?? "") === "" ? found(segment.text) : void 0;
3048
+ if (speaker === void 0) {
3049
+ folded.push(segment);
3050
+ continue;
3051
+ }
3052
+ folded.push({
3053
+ ...next,
3054
+ character: speaker.key
3055
+ });
3056
+ index += 1;
3057
+ }
3058
+ return folded;
3059
+ }
3060
+ /** How alike two situations have to be for a round about the second to bring nothing new, by the share of three-letter pieces they have in common. */
3061
+ const SAME_SITUATION = .85;
3062
+ const pieces = (text) => {
3063
+ const found = /* @__PURE__ */ new Set();
3064
+ const chars = [...text];
3065
+ for (let index = 0; index + 3 <= chars.length; index += 1) found.add(chars.slice(index, index + 3).join(""));
3066
+ return found;
3067
+ };
3068
+ /** Whether the same characters (or some of them) are asked about a situation that is, but for a few words, one they were already asked about in the turn. */
3069
+ function repeatsEarlier(signature, asked) {
3070
+ const [keys = "", text = ""] = signature.split("|");
3071
+ const now = new Set(keys.split(","));
3072
+ const mine = pieces(text);
3073
+ return asked.some((earlier) => {
3074
+ const [before = "", was = ""] = earlier.split("|");
3075
+ if (![...now].every((key) => before.split(",").includes(key))) return false;
3076
+ const theirs = pieces(was);
3077
+ const shared = [...mine].filter((piece) => theirs.has(piece)).length;
3078
+ const union = mine.size + theirs.size - shared;
3079
+ return union === 0 || shared / union >= SAME_SITUATION;
3080
+ });
3081
+ }
3051
3082
  /** The game master is asked to correct its output this many times before it is corrected for it. */
3052
3083
  const MAX_REFUSALS = 2;
3053
3084
  /** 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. */
@@ -3075,6 +3106,8 @@ var TurnEngine = class {
3075
3106
  /** 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. */
3076
3107
  working = /* @__PURE__ */ new Map();
3077
3108
  afterTurn;
3109
+ /** What a reflection the player asked for is cancelled with, as `stop` does for the turn. */
3110
+ reflectionCancels = /* @__PURE__ */ new Map();
3078
3111
  /** Chats whose characters away from the player are being asked about what fell due: one run at a time. */
3079
3112
  offstage = /* @__PURE__ */ new Set();
3080
3113
  constructor(boundaries, stores, problem = () => void 0, written = () => void 0) {
@@ -3100,12 +3133,75 @@ var TurnEngine = class {
3100
3133
  * 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
3101
3134
  * 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.
3102
3135
  */
3103
- beginOoc(owner, request) {
3136
+ beginOoc(owner, request, question = false) {
3104
3137
  const state = this.stateFor(owner);
3105
- state.ooc = { request };
3138
+ state.ooc = {
3139
+ request,
3140
+ ...question ? { question: true } : {}
3141
+ };
3106
3142
  state.previewWanted = false;
3107
3143
  }
3108
3144
  /**
3145
+ * The answer to an out-of-character question, which is the whole of that turn: nothing in the story changes and nobody is asked to act. It is not the game
3146
+ * master's to write, who knows what the player's character does not: it comes from what the player's character knows (what it remembers, knows exists, has
3147
+ * on it and sees where it is), so that nothing hidden can be given away.
3148
+ * @throws {Error} when the turn is not a question, it was already answered, or the answer is empty.
3149
+ */
3150
+ async answer(owner, run, signal) {
3151
+ const state = this.stateFor(owner);
3152
+ if (state.ooc?.question !== true) throw new Error("this turn is not an out-of-character question: there is nothing to answer");
3153
+ if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
3154
+ const text = (await run(await this.askedRequest(owner, state.ooc.request, signal), signal)).trim();
3155
+ if (text === "") throw new Error("the answer is empty");
3156
+ if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
3157
+ state.ooc.ruling = {
3158
+ legal: true,
3159
+ note: text.length > 1200 ? `${text.slice(0, 1199)}…` : text,
3160
+ question: true
3161
+ };
3162
+ state.phase = "between";
3163
+ return state.ooc.ruling;
3164
+ }
3165
+ /** What the player's character is given to answer a question with: the same as a character is given to act, with the question as the moment. */
3166
+ async askedRequest(owner, question, signal) {
3167
+ const store = this.storeOf(owner);
3168
+ const cast = store.cast();
3169
+ const member = cast.find((candidate) => candidate.character.control === "player");
3170
+ if (member === void 0) throw new Error("there is no player's character to answer for");
3171
+ const queryVector = await store.queryVector(question, signal);
3172
+ const memories = await this.boundaries().recaller.recall({
3173
+ member,
3174
+ situation: question,
3175
+ turn: owner.turn,
3176
+ policy: store.settings().memory,
3177
+ ...queryVector === void 0 ? {} : { queryVector }
3178
+ }, store.story, signal);
3179
+ const place = member.place === void 0 ? void 0 : store.place(member.place.location.id);
3180
+ const company = place === void 0 ? cast : place.here;
3181
+ const relationships = this.knownRelationships(member, company, question, cast, store);
3182
+ const carrying = store.carried(member.character.id);
3183
+ const affiliations = store.affiliations(member.character.id);
3184
+ const tracked = store.trackedFor(member.character.id, company.map((entry) => entry.character.id));
3185
+ return {
3186
+ member,
3187
+ cast,
3188
+ situation: question,
3189
+ attempt: 1,
3190
+ language: store.settings().prompts.language,
3191
+ turn: owner.turn,
3192
+ lookup: false,
3193
+ text: (id, variables) => store.text(id, variables),
3194
+ time: store.time(owner.turn),
3195
+ knowledge: store.knowledge(member.character.id, owner.turn, company.map((entry) => entry.character.id)),
3196
+ ...tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
3197
+ ...place === void 0 ? {} : { place },
3198
+ ...relationships.length === 0 ? {} : { relationships },
3199
+ ...carrying.length === 0 ? {} : { carrying },
3200
+ ...affiliations.length === 0 ? {} : { affiliations },
3201
+ ...memories.length === 0 ? {} : { memories }
3202
+ };
3203
+ }
3204
+ /**
3109
3205
  * The game master's ruling on an out-of-character command: it is legal unless it breaks the rules of the world or the player's own. The reason is
3110
3206
  * what the player is told. Either way the turn goes on to its output; only a legal ruling lets the command change anything.
3111
3207
  * @throws {Error} when the turn is not an out-of-character command, it was already ruled on, or the reason is empty or too long.
@@ -3113,6 +3209,7 @@ var TurnEngine = class {
3113
3209
  rule(owner, legal, reason) {
3114
3210
  const state = this.stateFor(owner);
3115
3211
  if (state.ooc === void 0) throw new Error("this turn is not an out-of-character command: there is nothing to rule on");
3212
+ if (state.ooc.question === true) throw new Error("this turn is an out-of-character question: answer it with ooc_answer");
3116
3213
  if (state.ooc.ruling !== void 0) throw new Error("this command was already ruled on");
3117
3214
  const note = reason.trim();
3118
3215
  if (note === "") throw new Error("give the reason, in plain words to the player");
@@ -3127,15 +3224,34 @@ var TurnEngine = class {
3127
3224
  /**
3128
3225
  * The game master judges what the player's character tries, before anything else in an ordinary turn: it works unless it is not viable or it breaks a rule of the
3129
3226
  * world or of the player. What does not work is played as a failed attempt for the player's character: nobody is asked to act on it.
3130
- * @throws {Error} when the turn is not an ordinary one, was already judged, or the reason is empty.
3227
+ * 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.
3228
+ * @throws {Error} when the turn is not an ordinary one, was already judged, the reason is empty, or `at` is not a place.
3131
3229
  */
3132
- judge(owner, allowed, reason) {
3230
+ judge(owner, allowed, reason, at) {
3133
3231
  const state = this.stateFor(owner);
3134
- if (state.ooc !== void 0) throw new Error("this turn is an out-of-character command: rule on it with ooc_ruling");
3232
+ 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"));
3135
3233
  if (state.phase !== "idle") throw new Error("the action is judged first, before anything else");
3136
3234
  if (state.judgement !== void 0) throw new Error("the action was already judged");
3137
3235
  const why = reason.trim();
3138
3236
  if (why === "") throw new Error("give the reason: what the character tries, and the rule or the fact that decides it");
3237
+ const place = at?.trim() ?? "";
3238
+ if (place !== "") {
3239
+ const store = this.storeOf(owner);
3240
+ const player = store.cast().find((member) => member.character.control === "player");
3241
+ const found = whereabouts(store.story.locations.list(), player?.place?.location, place);
3242
+ if (found.kind === "unknown") throw new Error(`there is no place "${place}" (list_locations shows the keys): name the place where the action happens, or leave "at" out when it happens where the character is`);
3243
+ if (found.kind === "elsewhere") {
3244
+ const name = player?.character.name ?? "The character";
3245
+ state.judgement = {
3246
+ allowed: false,
3247
+ reason: `${name} is at ${found.here.name}, not at ${found.target.name} where this happens: ${name} has to go there first`
3248
+ };
3249
+ return {
3250
+ ...state.judgement,
3251
+ elsewhere: true
3252
+ };
3253
+ }
3254
+ }
3139
3255
  state.judgement = {
3140
3256
  allowed,
3141
3257
  reason: why
@@ -3153,6 +3269,7 @@ var TurnEngine = class {
3153
3269
  /** Why an out-of-character command may not change anything yet, when it may not. */
3154
3270
  oocBlock(state) {
3155
3271
  if (state.ooc === void 0) return void 0;
3272
+ 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";
3156
3273
  if (state.ooc.ruling === void 0) return "this turn is an out-of-character command: rule on it first with ooc_ruling";
3157
3274
  return state.ooc.ruling.legal ? void 0 : "the command was refused: nothing changes; call narrate with no segments to tell the player";
3158
3275
  }
@@ -3166,7 +3283,7 @@ var TurnEngine = class {
3166
3283
  */
3167
3284
  async activate(owner, input, run, signal) {
3168
3285
  const state = this.stateFor(owner);
3169
- if (state.ooc !== void 0) throw new Error("an out-of-character command asks nobody to act: decree what happens with resolve_round, or narrate");
3286
+ 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");
3170
3287
  if (state.phase !== "idle" && state.phase !== "between") throw new Error(this.explain(state, "activate_characters"));
3171
3288
  if (this.judgeDue(state)) throw new Error(this.explain(state, "activate_characters"));
3172
3289
  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`);
@@ -3185,7 +3302,7 @@ var TurnEngine = class {
3185
3302
  if (keys.length === 0) throw new Error("there is no character to activate");
3186
3303
  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`);
3187
3304
  const signature = `${[...keys].sort().join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
3188
- if (state.asked.includes(signature)) 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");
3305
+ 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");
3189
3306
  state.situation = situation;
3190
3307
  state.cast = cast;
3191
3308
  state.recalled.clear();
@@ -3322,7 +3439,7 @@ var TurnEngine = class {
3322
3439
  */
3323
3440
  preview(owner, text) {
3324
3441
  const state = this.stateFor(owner);
3325
- if (state.ooc !== void 0) throw new Error("an out-of-character command shows no preview: rule on it with ooc_ruling");
3442
+ 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"));
3326
3443
  if (this.judgeDue(state)) throw new Error("judge the action first with judge_action");
3327
3444
  if (!this.storeOf(owner).settings().preview.enabled) throw new Error("this chat shows no preview: go on with activate_characters");
3328
3445
  if (state.previewed) throw new Error("a preview was already shown for this message: go on with activate_characters");
@@ -3386,6 +3503,7 @@ var TurnEngine = class {
3386
3503
  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)`);
3387
3504
  state.addressed = [...new Set(addressed)];
3388
3505
  if (state.ooc !== void 0) {
3506
+ 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");
3389
3507
  if (state.ooc.ruling?.legal !== true && segments.length > 0) throw new Error("the command was refused: deliver no segments, the player is told why");
3390
3508
  if (segments.some((segment) => segment.type === "utterance")) throw new Error("nobody was asked to speak in an out-of-character command: narrate only what the player perceives");
3391
3509
  return await this.deliver(owner, state, segments.map((segment) => ({
@@ -3403,7 +3521,7 @@ var TurnEngine = class {
3403
3521
  if (written === void 0) throw new Error("deliver the output: give its segments");
3404
3522
  return await this.deliver(owner, state, written, true, run);
3405
3523
  }
3406
- const typed = segments.map((segment) => segment.type === "utterance" ? {
3524
+ const typed = foldSpeakerLabels(segments, state.cast).map((segment) => segment.type === "utterance" ? {
3407
3525
  type: "utterance",
3408
3526
  character: segment.character ?? "",
3409
3527
  name: state.cast.find((member) => member.key === segment.character)?.character.name ?? segment.character ?? "",
@@ -3625,6 +3743,36 @@ var TurnEngine = class {
3625
3743
  await this.chains.get(chat);
3626
3744
  }
3627
3745
  }
3746
+ /**
3747
+ * Starts a reflection the player asked for: the records still waiting are written first, so that what the characters took in is there to
3748
+ * sort, and the pass then runs in the background. @throws {ReflectionRefusedError} while a turn is being played, or when a pass is already running.
3749
+ */
3750
+ async reflect(chat) {
3751
+ const store = this.stores(chat);
3752
+ if (store === void 0) throw new Error(`no story for chat ${chat}`);
3753
+ const turning = this.states.get(chat);
3754
+ if (turning !== void 0 && [
3755
+ "resolving",
3756
+ "retrying",
3757
+ "between"
3758
+ ].includes(turning.phase)) throw new ReflectionRefusedError("a turn is being played; reflect when it is over");
3759
+ const delivered = this.delivered.get(chat);
3760
+ if (delivered !== void 0 && store.pendingCommits().length > 0) this.write({
3761
+ chat,
3762
+ turn: delivered.turn
3763
+ }, delivered);
3764
+ await this.chains.get(chat);
3765
+ const cancel = new AbortController();
3766
+ this.reflectionCancels.set(chat, cancel);
3767
+ this.afterTurn.reflectNow({
3768
+ chat,
3769
+ turn: store.story.metadata.get().turns
3770
+ }, cancel.signal);
3771
+ }
3772
+ /** Whether a reflection is running for the chat. */
3773
+ reflecting(chat) {
3774
+ return this.afterTurn.isReflecting(chat);
3775
+ }
3628
3776
  /** Wait until the run of the keeper in flight, if any, has ended; nothing is started. */
3629
3777
  async idle(chat) {
3630
3778
  await this.chains.get(chat);
@@ -3651,6 +3799,7 @@ var TurnEngine = class {
3651
3799
  /** 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. */
3652
3800
  stop(chat) {
3653
3801
  this.states.get(chat)?.cancel.abort();
3802
+ this.reflectionCancels.get(chat)?.abort();
3654
3803
  }
3655
3804
  /** Resolves when nothing of the chat writes to its story any more: the records, what was made up being fitted in, the characters away. */
3656
3805
  async quiesce(chat) {
@@ -3662,6 +3811,8 @@ var TurnEngine = class {
3662
3811
  }
3663
3812
  forget(chat) {
3664
3813
  this.states.get(chat)?.cancel.abort();
3814
+ this.reflectionCancels.get(chat)?.abort();
3815
+ this.reflectionCancels.delete(chat);
3665
3816
  this.states.delete(chat);
3666
3817
  this.chains.delete(chat);
3667
3818
  this.delivered.delete(chat);
@@ -3708,10 +3859,11 @@ var TurnEngine = class {
3708
3859
  return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
3709
3860
  }
3710
3861
  explain(state, attempted) {
3862
+ 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";
3711
3863
  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";
3712
3864
  const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
3713
3865
  switch (state.phase) {
3714
- 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" : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : `nothing to ${attempted === "narrate" ? "deliver" : "resolve"} yet: call activate_characters first`;
3866
+ 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";
3715
3867
  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)}`;
3716
3868
  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)}`;
3717
3869
  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)}`;
@@ -3783,6 +3935,7 @@ var TurnEngine = class {
3783
3935
  situation: state.situation,
3784
3936
  turn: owner.turn,
3785
3937
  policy: store.settings().memory,
3938
+ ...store.settings().diagnostics.keepRuns ? { explain: true } : {},
3786
3939
  ...queryVector === void 0 ? {} : { queryVector }
3787
3940
  }, store.story, signal) : state.recalled.get(key) ?? [];
3788
3941
  if (number === 1 && memories.length > 0) state.recalled.set(key, memories);
@@ -3800,6 +3953,7 @@ var TurnEngine = class {
3800
3953
  cast,
3801
3954
  situation: state.situation,
3802
3955
  attempt: number,
3956
+ language: store?.settings().prompts.language ?? "en",
3803
3957
  turn: owner.turn,
3804
3958
  ...away ? { away: true } : {},
3805
3959
  lookup: store?.settings().memory.lookup ?? false,
@@ -3837,10 +3991,13 @@ var TurnEngine = class {
3837
3991
  };
3838
3992
  } catch (error) {
3839
3993
  if (signal.aborted) throw error;
3994
+ const reason = error instanceof Error ? error.message : String(error);
3995
+ this.problem(`${member.character.name} could not act: ${reason}`);
3840
3996
  return {
3841
3997
  character: key,
3842
3998
  name: member.character.name,
3843
- reason: error instanceof Error ? error.message : String(error)
3999
+ reason,
4000
+ technical: true
3844
4001
  };
3845
4002
  }
3846
4003
  }));
@@ -3867,7 +4024,7 @@ var TurnEngine = class {
3867
4024
  if (!present.has(relation.toId) && !relevant.has(relation.toId)) return [];
3868
4025
  const other = cast.find((candidate) => candidate.character.id === relation.toId);
3869
4026
  return other === void 0 || other.key === member.key ? [] : [{
3870
- name: other.character.name,
4027
+ name: referent(other.character),
3871
4028
  label: relation.label,
3872
4029
  summary: relation.summary,
3873
4030
  present: present.has(relation.toId),
@@ -4453,6 +4610,7 @@ function apply(ctx) {
4453
4610
  ctx.effect(() => ctx.roleplayOrchestration.replace({ committer: recordKeeper({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: record keeper");
4454
4611
  ctx.effect(() => ctx.roleplayOrchestration.replace({ judge: triggerJudge({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: trigger judge");
4455
4612
  ctx.effect(() => ctx.roleplayOrchestration.replace({ strategist: factionStrategist({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: faction strategist");
4613
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ reflector: memoryReflector({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: reflection");
4456
4614
  ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: world author");
4457
4615
  ctx.effect(() => ctx.roleplayOrchestration.replace({ suggester: suggestionWriter({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: suggestions");
4458
4616
  ctx.effect(() => ctx.roleplayState.bind((agentSessionId) => {
@@ -4506,6 +4664,14 @@ function apply(ctx) {
4506
4664
  }
4507
4665
  })].sort((a, b) => Number(b.name === PREVIEW_TOOL) - Number(a.name === PREVIEW_TOOL));
4508
4666
  for (const tool of tools) ctx.tools.register(tool);
4667
+ ctx.effect(() => {
4668
+ ctx.roleplayOrchestration.reflect = (chat) => engine.reflect(chat);
4669
+ ctx.roleplayOrchestration.reflecting = (chat) => engine.reflecting(chat);
4670
+ return () => {
4671
+ ctx.roleplayOrchestration.reflect = () => Promise.reject(/* @__PURE__ */ new Error("the orchestration is not running"));
4672
+ ctx.roleplayOrchestration.reflecting = () => false;
4673
+ };
4674
+ }, "roleplay: reflection control");
4509
4675
  ctx.effect(() => {
4510
4676
  ctx.roleplayOrchestration.settle = (chat) => engine.idle(chat);
4511
4677
  return () => {