@dsh-agentic-roleplay/core 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/lib/{access-CXtaZNbx.js → access-DAw54-NI.js} +6 -15
  2. package/lib/{authoring-tools--6V1pIIL.js → authoring-tools-4NgDhIJV.js} +116 -13
  3. package/lib/authoring.js +38 -8
  4. package/lib/{child-C9nPIy9j.js → child-D3QUNb3m.js} +121 -2
  5. package/lib/client.js +1389 -475
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-CtG-bDzz.js → gallery-Ct6nm4UQ.js} +3 -3
  10. package/lib/{generator-nLoPM5MF.js → generator-CI8fOnXy.js} +9 -3
  11. package/lib/helper.js +22 -1
  12. package/lib/{hooks-DORky4KT.js → hooks-BNeoGMHZ.js} +1342 -293
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +444 -24
  15. package/lib/jail-BIF79PJO.js +107 -0
  16. package/lib/{library-CH-ahlm0.js → library-BF9ZMSFz.js} +3 -3
  17. package/lib/{lorebook-author-tools-BrVde1N-.js → lorebook-author-tools-DBk-V0hp.js} +7 -7
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-B0hConSw.js → narration-xvErE2yp.js} +34 -3
  20. package/lib/orchestration.js +915 -59
  21. package/lib/{pack-jail-Bk82pX9t.js → pack-jail-C8EyX9Ix.js} +18 -14
  22. package/lib/{packs-ELfh8yh1.js → packs-S0SzrVv-.js} +2 -2
  23. package/lib/{presenter-agent-UKbKYXMO.js → presenter-agent-Bc478nTA.js} +11 -8
  24. package/lib/{preset-D9Sfc8sf.js → preset-SJZyw0kt.js} +4 -4
  25. package/lib/{preset-author-tools-B3pFL1-e.js → preset-author-tools-CzogjK42.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-BRt4Xsy4.js → presets-DQ5rioMh.js} +251 -49
  28. package/lib/{reflection-CHiHsY4Y.js → reflection-buQiSdvq.js} +17 -609
  29. package/lib/service-mRKwpWjX.js +140 -0
  30. package/lib/{text-CzqhC8sT.js → text-Dfv8S8eq.js} +36 -2
  31. package/lib/{turn-guard-B53qOWEU.js → turn-guard-BSAba8sp.js} +3 -3
  32. package/package.json +3 -3
  33. package/prompts/en/import/finish-ok.md +1 -1
  34. package/prompts/en/import/generator.md +1 -1
  35. package/prompts/en/import/style.md +1 -1
  36. package/prompts/en/import/variables.md +3 -1
  37. package/prompts/en/roleplay/character-decide.md +1 -1
  38. package/prompts/en/roleplay/character-lookup.md +1 -1
  39. package/prompts/en/roleplay/decide-errand.md +1 -0
  40. package/prompts/en/roleplay/decide-message.md +1 -0
  41. package/prompts/en/roleplay/decide-reuse.md +3 -0
  42. package/prompts/en/roleplay/decide-variable.md +1 -0
  43. package/prompts/en/roleplay/dream.md +1 -0
  44. package/prompts/en/roleplay/gate-repeat.md +1 -0
  45. package/prompts/en/roleplay/image-presenter.md +1 -0
  46. package/prompts/en/roleplay/track-values.md +1 -0
  47. package/prompts/en/roleplay/track-variables.md +1 -0
  48. package/prompts/zh/import/finish-ok.md +1 -1
  49. package/prompts/zh/import/generator.md +1 -1
  50. package/prompts/zh/import/style.md +1 -1
  51. package/prompts/zh/import/variables.md +3 -1
  52. package/prompts/zh/roleplay/character-decide.md +1 -1
  53. package/prompts/zh/roleplay/character-lookup.md +1 -1
  54. package/prompts/zh/roleplay/decide-errand.md +1 -0
  55. package/prompts/zh/roleplay/decide-message.md +1 -0
  56. package/prompts/zh/roleplay/decide-reuse.md +3 -0
  57. package/prompts/zh/roleplay/decide-variable.md +1 -0
  58. package/prompts/zh/roleplay/dream.md +1 -0
  59. package/prompts/zh/roleplay/gate-repeat.md +1 -0
  60. package/prompts/zh/roleplay/image-presenter.md +1 -0
  61. package/prompts/zh/roleplay/track-values.md +1 -0
  62. package/prompts/zh/roleplay/track-variables.md +1 -0
@@ -1,12 +1,13 @@
1
- import { l as roleplaySessionOf, t as promptFor } from "./access-CXtaZNbx.js";
2
- import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-B0hConSw.js";
3
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CzqhC8sT.js";
4
- import { T as estimateAnswer, _ as estimateTokens, a as childTrace, b as addTokens, g as blockText, h as requestsOf, l as runChild, n as childModel, r as childSampling, v as tokensOf, y as NO_TOKENS } from "./child-C9nPIy9j.js";
1
+ import { C as addTokens, D as finishOf, E as cutOff, O as estimateAnswer, S as NO_TOKENS, a as childTrace, b as estimateTokens, f as tracerOf, j as roleplaySessionOf, l as runChild, n as childModel, r as childSampling, u as TurnTraces, v as requestsOf, x as tokensOf, y as blockText } from "./child-D3QUNb3m.js";
2
+ import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-xvErE2yp.js";
3
+ import { t as promptFor } from "./access-DAw54-NI.js";
4
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-Dfv8S8eq.js";
5
+ import { n as storyRoots } from "./service-mRKwpWjX.js";
5
6
  import { dirname, join } from "node:path";
6
- import { DAY, ENGAGEMENT_GRACE, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, describeValue, holidaysOn, inAudience, isSessionId, itemKey, localTime, locationKey, nextOccurrence, nextTimeOfDay, occurrenceAt, parseInstant, planItemChange, planVariableChange, readCalendar, rollPlain, seasonOf, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
7
+ import { DAY, ENGAGEMENT_GRACE, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, describeValue, holidaysOn, inAudience, isSessionId, itemKey, localTime, locationKey, mentioned, nextOccurrence, nextTimeOfDay, occurrenceAt, overlap, parseInstant, planItemChange, planVariableChange, readCalendar, rollPlain, seasonOf, sessionDatabase, sessionFolder, shownVariables, tokens } from "@dsh-agentic-roleplay/state";
7
8
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
8
9
  import { readFile, stat } from "node:fs/promises";
9
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
10
+ import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
10
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
11
12
  import { fileURLToPath } from "node:url";
12
13
  import { Service } from "@deepseek-ai/cordis";
@@ -707,7 +708,7 @@ function plotReferenceProblems(plots, entities) {
707
708
  return plots.flatMap((plot) => plot.participants.filter((participant) => !known.has(participant)).map((participant) => `plot "${plot.id}" names unknown participant "${participant}"`));
708
709
  }
709
710
  // src/host/sessions/usage.ts
710
- const KEY$5 = "usage";
711
+ const KEY$6 = "usage";
711
712
  const isCount = (value) => typeof value === "object" && value !== null && [
712
713
  "input",
713
714
  "cached",
@@ -716,7 +717,7 @@ const isCount = (value) => typeof value === "object" && value !== null && [
716
717
  const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
717
718
  /** What each turn used, oldest first. The record belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
718
719
  function readUsage(session) {
719
- const stored = session.metadata.getValue(KEY$5);
720
+ const stored = session.metadata.getValue(KEY$6);
720
721
  return Array.isArray(stored) ? stored.filter(isUsage) : [];
721
722
  }
722
723
  /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
@@ -741,7 +742,7 @@ function addUsage(session, turn, who, tokens, masterMs) {
741
742
  if (at === -1) all.push(next);
742
743
  else all[at] = next;
743
744
  all.sort((a, b) => a.turn - b.turn);
744
- session.metadata.setValue(KEY$5, all);
745
+ session.metadata.setValue(KEY$6, all);
745
746
  }
746
747
  // src/host/translate/language.ts
747
748
  const STORY_LANGUAGES = ["en", "zh"];
@@ -1025,6 +1026,615 @@ function parseCharacterAction(value) {
1025
1026
  ...told === "" ? {} : { account: told }
1026
1027
  };
1027
1028
  }
1029
+ // src/host/orchestration/referent.ts
1030
+ /**
1031
+ * How a person is named wherever the text may go on to say what they do: the name with the pronouns the world gave them, or the gender when only that is given.
1032
+ * A model that is not told guesses, and a wrong guess written into a record or a narration is never corrected; nothing is made up when the world says neither.
1033
+ */
1034
+ function referent(character) {
1035
+ const mark = [character.pronouns, character.gender].find((text) => text !== void 0 && text.trim() !== "")?.trim();
1036
+ return mark === void 0 ? character.name : `${character.name} (${mark})`;
1037
+ }
1038
+ // src/host/orchestration/defaults.ts
1039
+ const ENGLISH = translator("en");
1040
+ /** What the instructions say about how long each part of a character's answer may run. */
1041
+ const limitVariables = (language) => {
1042
+ const limits = answerLimits(language);
1043
+ return {
1044
+ thoughtLimit: limits.thought,
1045
+ intentLimit: limits.intent,
1046
+ utteranceLimit: limits.utterance
1047
+ };
1048
+ };
1049
+ function describe(character, tr) {
1050
+ const lines = [tr("You are {name}.", { name: character.name })];
1051
+ if (character.aliases.length > 0) lines.push(tr("You are also called {names}.", { names: character.aliases.join(tr(", ")) }));
1052
+ const facts = [
1053
+ character.age === void 0 ? void 0 : tr("age: {value}", { value: character.age }),
1054
+ character.gender === void 0 ? void 0 : tr("gender: {value}", { value: character.gender }),
1055
+ character.pronouns === void 0 ? void 0 : tr("pronouns: {value}", { value: character.pronouns })
1056
+ ].filter((fact) => fact !== void 0);
1057
+ if (facts.length > 0) lines.push(facts.join(tr("; ")) + tr("."));
1058
+ for (const [label, text] of [
1059
+ ["Summary", character.summary],
1060
+ ["Personality", character.personality],
1061
+ ["Background", character.background],
1062
+ ["Appearance", character.appearance],
1063
+ ["How you speak", character.speech.style]
1064
+ ]) if (text.trim() !== "") lines.push(`${tr(label)}${tr(": ")}${text.trim()}`);
1065
+ return lines.join("\n");
1066
+ }
1067
+ /** At most this many features and ways out of a place are told at once. */
1068
+ const SHOWN_FEATURES = 12;
1069
+ const SHOWN_EXITS = 12;
1070
+ const sentence = (text) => {
1071
+ return (/^[^.!?。!?]*[.!?。!?]?/u.exec(text.trim())?.[0] ?? text).trim();
1072
+ };
1073
+ /** At most this many things are listed at once: the rest are said to be there and left for a closer look. */
1074
+ const SHOWN_ITEMS = 12;
1075
+ /** One thing in a sentence: how many, what state it is in, where it is. */
1076
+ function describeItem(item, { withKeys }, tr = ENGLISH) {
1077
+ const name = `${item.quantity > 1 ? `${item.quantity} ` : ""}${item.name}${item.quality === "" ? "" : ` (${item.quality})`}`;
1078
+ const extra = [
1079
+ item.hidden ? tr("hidden") : "",
1080
+ item.state === void 0 ? "" : item.state,
1081
+ item.where ?? ""
1082
+ ].filter((part) => part !== "").join(tr(", "));
1083
+ const inside = item.contents === void 0 ? "" : tr(" holding {things}", { things: item.contents.join(tr(", ")) });
1084
+ return `${withKeys ? `${item.key}: ` : ""}${name}${extra === "" ? "" : ` [${extra}]`}${inside}`;
1085
+ }
1086
+ /** A list of things, capped. */
1087
+ function describeItems(items, options, tr = ENGLISH) {
1088
+ return `${items.slice(0, SHOWN_ITEMS).map((item) => describeItem(item, options, tr)).join(tr("; "))}${items.length > SHOWN_ITEMS ? tr("; and {count} more", { count: items.length - SHOWN_ITEMS }) : ""}`;
1089
+ }
1090
+ /** What someone in a place is told about it: what it is like, what can be pointed at, and the ways out. */
1091
+ function describePlace(view, { withKeys }, tr = ENGLISH) {
1092
+ const { location, exits } = view;
1093
+ const lines = [`${location.name}${withKeys ? ` (${view.key})` : ""}${location.description === "" ? "" : `: ${location.description}`}`];
1094
+ if (location.features.length > 0) {
1095
+ const shown = location.features.slice(0, SHOWN_FEATURES).map((feature) => `${withKeys ? `${feature.key}: ` : ""}${feature.name}${feature.description === "" ? "" : ` - ${sentence(feature.description)}`}`);
1096
+ lines.push(`${tr("Things here: ")}${shown.join(tr("; "))}${location.features.length > SHOWN_FEATURES ? tr("; and {count} more", { count: location.features.length - SHOWN_FEATURES }) : ""}`);
1097
+ }
1098
+ if (exits.length > 0) {
1099
+ const shown = exits.slice(0, SHOWN_EXITS).map(({ key, name, exit }) => `${withKeys ? `${key}: ` : ""}${name}${exit.description === "" ? "" : ` (${sentence(exit.description)})`}${exit.state === "open" ? "" : ` [${tr(exit.state)}${exit.note === "" ? "" : `: ${exit.note}`}]`}`);
1100
+ lines.push(`${tr("Ways out: ")}${shown.join(tr("; "))}${exits.length > SHOWN_EXITS ? tr("; and {count} more", { count: exits.length - SHOWN_EXITS }) : ""}`);
1101
+ }
1102
+ if (view.items !== void 0 && view.items.length > 0) lines.push(`${tr("Lying about: ")}${describeItems(view.items, { withKeys }, tr)}`);
1103
+ return lines;
1104
+ }
1105
+ /** How long the player has to have been away for it to be worth telling the game master. */
1106
+ const NOTICEABLE_ABSENCE = 5 * MINUTE;
1107
+ /** What the game master is told about time at the start of a turn, and how it passes. */
1108
+ function timeNotice(time, language, tr) {
1109
+ const now = tr("Time: {time}.", { time: describeTime(time.now, language) });
1110
+ if (time.now.mode === "simulated") return `${now} ${tr("The story's time moves only as you say: each round takes what you give it (elapsed_seconds in resolve_round, or the default), and advance_time skips ahead.")}`;
1111
+ const away = time.away !== void 0 && time.away >= NOTICEABLE_ABSENCE ? ` ${tr("The player was away for {duration} of real time and the story went on meanwhile: characters have been about their own business, so do not assume anyone is where or as the player left them unless the records say so.", { duration: describeDuration(time.away, language) })}` : "";
1112
+ return `${now} ${tr("The story's time follows the real clock: it cannot be skipped, and each round takes as long as it really took.")}${away}`;
1113
+ }
1114
+ /** What a character is told of its day, its commitments and what it is after. */
1115
+ function describeAgenda(agenda, now, tr = ENGLISH, language = "en") {
1116
+ const { zone } = agenda;
1117
+ const when = (instant) => describeWhen(instant, now, zone, language);
1118
+ const at = (place) => place === void 0 ? "" : tr(" at {place}", { place });
1119
+ const lines = [];
1120
+ if (agenda.now !== void 0) lines.push(tr("Your day, now: {activity}{place}, until {until}{note}.", {
1121
+ activity: agenda.now.activity,
1122
+ place: at(agenda.now.place),
1123
+ until: when(agenda.now.until),
1124
+ note: agenda.now.interruptible ? "" : tr(" (not something you would drop lightly)")
1125
+ }));
1126
+ if (agenda.now === void 0 && agenda.offDay !== void 0) lines.push(tr("What is happening to you has taken you from your day for now; you take it up again {until}.", { until: when(agenda.offDay.until) }));
1127
+ if (agenda.next !== void 0) lines.push(tr("Your day, next: {activity}{place}, from {from}.", {
1128
+ activity: agenda.next.activity,
1129
+ place: at(agenda.next.place),
1130
+ from: when(agenda.next.at)
1131
+ }));
1132
+ for (const engagement of agenda.engagements) {
1133
+ const values = {
1134
+ title: engagement.title,
1135
+ place: at(engagement.place),
1136
+ with: engagement.with.length === 0 ? "" : tr(", with {names}", { names: engagement.with.join(tr(", ")) }),
1137
+ at: when(engagement.at)
1138
+ };
1139
+ lines.push(engagement.overdue ? tr("You were to: {title}{place}{with}, at {at}, which has passed and is still open.", values) : tr("You are due to: {title}{place}{with}, at {at}.", values));
1140
+ }
1141
+ if (agenda.goals.length > 0) {
1142
+ lines.push(tr("What you are after:"));
1143
+ for (const goal of agenda.goals) {
1144
+ const by = goal.deadline === void 0 ? "" : goal.overdue ? tr(", by {deadline}, which has passed", { deadline: when(goal.deadline) }) : tr(", by {deadline}", { deadline: when(goal.deadline) });
1145
+ lines.push(`- ${goal.name} (${goal.type})${by}${goal.description === "" ? "" : `${tr(": ")}${sentence(goal.description)}`}${goal.plan.length === 0 ? "" : tr(" Next: {plan}.", { plan: goal.plan.join(tr("; ")) })}`);
1146
+ }
1147
+ }
1148
+ return lines;
1149
+ }
1150
+ /** What the game master is told of the characters' days at the start of a turn; nothing when there is nothing to tell. */
1151
+ function describeSceneAgenda(agenda, now, tr = ENGLISH, language = "en") {
1152
+ const lines = [];
1153
+ const join = (entries) => entries.join(tr("; "));
1154
+ if (agenda.moved.length > 0) lines.push(tr("By their routines since you last looked: {moves}.", { moves: join(agenda.moved.map((move) => tr("{name} went to {place} ({activity})", {
1155
+ name: move.name,
1156
+ place: move.to,
1157
+ activity: move.activity
1158
+ }))) }));
1159
+ if (agenda.here.length > 0) lines.push(tr("With the player's character, and their days: {days}. The characters decide for themselves whether to keep to their day; the moment may keep them.", { days: join(agenda.here.map((entry) => `${entry.name}${tr(": ")}${entry.note}`)) }));
1160
+ if (agenda.asleep.length > 0) lines.push(tr("Asleep now: {names}. An asleep character takes part only if what the player does wakes them: name them in wakes when you ask them, and show them waking.", { names: join(agenda.asleep.map((entry) => tr("{name} (until {until})", {
1161
+ name: `${entry.name} [${entry.key}]`,
1162
+ until: describeWhen(entry.until, now, agenda.zone, language)
1163
+ }))) }));
1164
+ if (agenda.engagements.length > 0) {
1165
+ const entries = agenda.engagements.map((engagement) => {
1166
+ const values = {
1167
+ title: engagement.title,
1168
+ with: engagement.with.join(tr(", ")),
1169
+ place: engagement.place === void 0 ? "" : tr(", at {place}", { place: engagement.place }),
1170
+ when: describeWhen(engagement.at, now, agenda.zone, language)
1171
+ };
1172
+ return engagement.overdue ? tr("\"{title}\" ({with}{place}) was due {when} and is still open", values) : tr("\"{title}\" ({with}{place}) is due {when}", values);
1173
+ });
1174
+ lines.push(tr("Commitments due soon or overdue: {entries}.", { entries: join(entries) }));
1175
+ }
1176
+ return lines.join("\n");
1177
+ }
1178
+ /** In words, how a character stands with another, from the numbers of its profile; nothing for what is unremarkable. */
1179
+ function describeAttitude(relation, tr = ENGLISH) {
1180
+ return [
1181
+ relation.familiarity >= .7 ? tr("knows them well") : relation.familiarity <= .15 ? tr("barely knows them") : "",
1182
+ relation.trust >= .4 ? tr("trusts them") : relation.trust <= -.4 ? tr("distrusts them") : "",
1183
+ relation.affinity >= .4 ? tr("is fond of them") : relation.affinity <= -.4 ? tr("dislikes them") : "",
1184
+ relation.tension >= .5 ? tr("things are strained between them") : ""
1185
+ ].filter((part) => part !== "").join(tr(", "));
1186
+ }
1187
+ function whereIs(member, tr = ENGLISH) {
1188
+ const place = member.place;
1189
+ if (place === void 0) return "";
1190
+ return [place.position, place.feature === void 0 ? "" : tr("at {feature}", { feature: place.feature.name })].filter((part) => part !== "").join(tr(", "));
1191
+ }
1192
+ function present(cast, self, tr) {
1193
+ return cast.map((member) => {
1194
+ const { key, character, state } = member;
1195
+ const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
1196
+ const where = whereIs(member);
1197
+ return `- ${key === self ? character.name : referent(character)}${key === self ? tr(" (you)") : ""}${where === "" ? "" : ` (${where})`}${seen.length > 0 ? `${tr(": ")}${seen.join(tr("; "))}` : ""}`;
1198
+ }).join("\n");
1199
+ }
1200
+ /** A bounded, advisory order for who is most likely to need a turn; reachability still governs activation. */
1201
+ function describeActivationCandidates(cast, input, story, tr = ENGLISH) {
1202
+ const player = cast.find((member) => member.character.control === "player");
1203
+ if (player === void 0) return "";
1204
+ const named = mentioned(input, cast.map((member) => member.character));
1205
+ const cues = tokens(input);
1206
+ const candidates = cast.filter((member) => member.character.control === "agent").map((member) => {
1207
+ const relation = story.relationships.get(member.character.id, player.character.id);
1208
+ const here = member.place === void 0 || player.place === void 0 || member.place.location.id === player.place.location.id;
1209
+ const goal = story.intents.list(member.character.id, { status: "active" }).map((intent) => ({
1210
+ intent,
1211
+ match: overlap(cues, `${intent.name} ${intent.description}`, [])
1212
+ })).sort((a, b) => b.match - a.match)[0];
1213
+ const factionGoal = story.factionMemberships.ofCharacter(member.character.id, "active").flatMap((membership) => story.factionIntents.list(membership.factionId, { status: "active" }).map((intent) => ({
1214
+ intent,
1215
+ match: overlap(cues, `${intent.name} ${intent.description}`, []) * membership.commitment
1216
+ }))).sort((a, b) => b.match - a.match)[0];
1217
+ return {
1218
+ member,
1219
+ reasons: [
1220
+ named.has(member.character.id) ? tr("named in the move") : "",
1221
+ here ? tr("in the scene") : "",
1222
+ (goal?.match ?? 0) >= 2 ? tr("own goal: {goal}", { goal: goal.intent.name }) : "",
1223
+ (factionGoal?.match ?? 0) >= 2 ? tr("faction pressure: {goal}", { goal: factionGoal.intent.name }) : "",
1224
+ relation !== void 0 && relation.tension >= .5 ? tr("high tension toward the player") : "",
1225
+ relation !== void 0 && relation.trust <= -.4 ? tr("distrusts the player") : "",
1226
+ relation !== void 0 && Math.abs(relation.affinity) >= .4 ? relation.affinity > 0 ? tr("cares about the player") : tr("dislikes the player") : ""
1227
+ ].filter((reason) => reason !== ""),
1228
+ score: (named.has(member.character.id) ? 4 : 0) + (here ? 2 : 0) + Math.min(2, (goal?.match ?? 0) / 2) + Math.min(2, (factionGoal?.match ?? 0) / 2) + (relation?.tension ?? 0) + Math.max(0, -(relation?.trust ?? 0)) * .5 + Math.abs(relation?.affinity ?? 0) * .5
1229
+ };
1230
+ }).filter((entry) => entry.score > 0).sort((a, b) => b.score - a.score || a.member.key.localeCompare(b.member.key)).slice(0, 5);
1231
+ if (candidates.length === 0) return "";
1232
+ return `${tr("Likely characters to activate, in priority order (advice only; activate only whoever the moment actually reaches):")}\n${candidates.map(({ member, reasons }) => `- ${member.character.name} (${member.key}): ${reasons.join(tr(", ")) || tr("socially implicated")}`).join("\n")}`;
1233
+ }
1234
+ function said(entry, tr) {
1235
+ return entry.utterance === void 0 ? tr("- {name} intended: {intent} ({result}) {summary}", {
1236
+ name: entry.name,
1237
+ intent: entry.intent,
1238
+ result: entry.result,
1239
+ summary: entry.summary
1240
+ }) : tr("- {name} said \"{utterance}\" and intended: {intent} ({result}) {summary}", {
1241
+ name: entry.name,
1242
+ utterance: entry.utterance,
1243
+ intent: entry.intent,
1244
+ result: entry.result,
1245
+ summary: entry.summary
1246
+ });
1247
+ }
1248
+ function age(at, now, tr) {
1249
+ if (at === void 0 || now === void 0) return tr("some time ago");
1250
+ const seconds = Math.max(0, Math.floor((now - at) / 1e3));
1251
+ if (seconds < 60) return tr("just now");
1252
+ const amount = Math.floor(seconds / (seconds >= 86400 ? 86400 : seconds >= 3600 ? 3600 : 60));
1253
+ if (seconds >= 86400) return amount === 1 ? tr("1 day ago") : tr("{amount} days ago", { amount });
1254
+ if (seconds >= 3600) return amount === 1 ? tr("1 hour ago") : tr("{amount} hours ago", { amount });
1255
+ return amount === 1 ? tr("1 minute ago") : tr("{amount} minutes ago", { amount });
1256
+ }
1257
+ /** What a character remembers, in the way it remembers it: what is faded or vague is told as such, and what it is sure or doubtful of. */
1258
+ function remembered(memories, tr, now) {
1259
+ return memories.map((memory) => {
1260
+ const clarity = memory.clarity === "clear" ? [] : [memory.clarity === "faded" ? tr("the details are fuzzy") : tr("you barely remember")];
1261
+ const sure = memory.confidence === "sure" ? [tr("you are sure of it")] : memory.confidence === "doubtful" ? [tr("you doubt it")] : [];
1262
+ const against = memory.disputed === true ? [tr("something you have seen since speaks against it")] : [];
1263
+ return `- (${[
1264
+ age(memory.at, now, tr),
1265
+ ...clarity,
1266
+ ...sure,
1267
+ ...against,
1268
+ ...memory.linked === true ? [tr("it comes to mind with the rest")] : []
1269
+ ].join(tr(", "))}) ${memory.text}`;
1270
+ }).join("\n");
1271
+ }
1272
+ /** Every character is told the same thing about the scene, plus who it is and what it remembers. */
1273
+ const sharedContext = { brief(request) {
1274
+ const { member, cast, situation, attempt, earlier, reaction, previous, memories, place, relationships, knowledge, affiliations, carrying, time, agenda } = request;
1275
+ const language = languageOf$1(request.language);
1276
+ const tr = translator(language);
1277
+ const list = (entries) => entries.join(tr("; "));
1278
+ const company = place === void 0 ? cast : place.here;
1279
+ const sections = [
1280
+ `${tr("Situation:")}\n${situation}`,
1281
+ ...time === void 0 ? [] : [tr("Now: {time}.", { time: describeTime(time, language) })],
1282
+ ...place === void 0 ? [] : [`${tr("Where you are:")}\n${describePlace(place, { withKeys: false }, tr).join("\n")}`],
1283
+ `${tr("Present:")}\n${present(company, member.key, tr)}`
1284
+ ];
1285
+ if (request.upcoming !== void 0 && request.upcoming.length > 0) sections.push(`${tr("What you know is coming:")}\n${request.upcoming.map((entry) => `- ${entry.text}${entry.when === void 0 ? "" : ` (${entry.when})`}`).join("\n")}`);
1286
+ if (request.cues !== void 0 && request.cues.length > 0) sections.push(`${tr("Just now you notice:")}\n${request.cues.map((cue) => `- ${cue}`).join("\n")}`);
1287
+ if (request.tracked !== void 0 && request.tracked.self !== "") sections.push(`${tr("How you are (what you can tell of yourself):")}\n${request.tracked.self}`);
1288
+ if (request.tracked !== void 0 && request.tracked.others.length > 0) sections.push(`${tr("What you can tell of the others here:")}\n${request.tracked.others.map((other) => `- ${other.name}: ${other.text}`).join("\n")}`);
1289
+ const day = agenda === void 0 || time === void 0 ? [] : describeAgenda(agenda, time.now, tr, language);
1290
+ if (day.length > 0) sections.push(`${tr("Your day and what you are after (plans, not orders: keep them, put them off or drop them as the moment and your character suggest):")}\n${day.join("\n")}`);
1291
+ if (request.dreaming === true) sections.push(tr("You are asleep and dreaming, and the player's character is in your dream. What you intend and say is the dream's: it may shift, blur and be odd, and it is not something you do awake. Answer from what the dream would make of the moment, out of your own fears, wants and what you have not said."));
1292
+ if (carrying !== void 0 && carrying.length > 0) sections.push(`${tr("What you have on you:")}\n${describeItems(carrying, { withKeys: false }, tr)}`);
1293
+ if (relationships !== void 0 && relationships.length > 0) sections.push(`${tr("How you stand with people who bear on this moment (your own view, not objective fact):")}\n${relationships.map((relation) => {
1294
+ const attitude = describeAttitude(relation, tr);
1295
+ return `- ${relation.name}${relation.present ? tr(" (here)") : tr(" (not here)")} — ${relation.label}${relation.summary === "" ? "" : `${tr(": ")}${relation.summary}`}${attitude === "" ? "" : ` [${attitude}]`}`;
1296
+ }).join("\n")}`);
1297
+ if (affiliations !== void 0 && affiliations.length > 0) sections.push(`${tr("Your affiliations (their goals are pressures and commitments, not commands):")}\n${affiliations.map((entry) => {
1298
+ const position = [entry.role, entry.rank].filter(Boolean).join(tr(", ")) || tr("member");
1299
+ const goals = entry.goals.length === 0 ? "" : tr(" Goals: {goals}.", { goals: list(entry.goals) });
1300
+ const state = entry.publicState === "" ? "" : ` ${entry.publicState}`;
1301
+ const attitude = entry.relationship === void 0 ? "" : describeAttitude(entry.relationship, tr);
1302
+ return tr("- {name}: {position}; {status}; commitment {commitment}.", {
1303
+ name: entry.name,
1304
+ position,
1305
+ status: entry.status,
1306
+ commitment: entry.commitment.toFixed(2)
1307
+ }) + `${state}${goals}${attitude === "" ? "" : tr(" Your view: {attitude}.", { attitude })}`;
1308
+ }).join("\n")}`);
1309
+ if (knowledge !== void 0) {
1310
+ const shown = (entries) => list(entries.slice(0, 30)) + (entries.length > 30 ? tr("; and {count} more you can recall if needed", { count: entries.length - 30 }) : "");
1311
+ const lines = [
1312
+ knowledge.characters.length === 0 ? void 0 : `${tr("People: ")}${shown(knowledge.characters)}`,
1313
+ knowledge.factions.length === 0 ? void 0 : `${tr("Factions: ")}${shown(knowledge.factions)}`,
1314
+ knowledge.locations.length === 0 ? void 0 : `${tr("Places: ")}${shown(knowledge.locations)}`,
1315
+ knowledge.routes.length === 0 ? void 0 : `${tr("Routes: ")}${shown(knowledge.routes)}`,
1316
+ knowledge.items.length === 0 ? void 0 : `${tr("Things: ")}${shown(knowledge.items)}`,
1317
+ knowledge.lore.length === 0 ? void 0 : `${tr("Background you know, to read with recall_my_lore when it bears on the moment: ")}${shown(knowledge.lore)}`
1318
+ ].filter((line) => line !== void 0);
1319
+ if (lines.length > 0) sections.push(`${tr("What you know exists (this does not tell you where it is now or what state it is in):")}\n${lines.join("\n")}`);
1320
+ }
1321
+ if (memories !== void 0 && memories.length > 0) sections.splice(1, 0, `${tr("What you remember that bears on this (only what you took in yourself; do not claim to remember more, and be unsure of what is fuzzy):")}\n${remembered(memories, tr, time?.now)}`);
1322
+ else if (memories !== void 0) sections.splice(1, 0, tr("What you remember that bears on this: nothing comes to mind."));
1323
+ if (earlier !== void 0 && earlier.length > 0) sections.push(`${tr("Earlier in this scene, before this moment:")}\n${earlier.map((entry) => said(entry, tr)).join("\n")}`);
1324
+ if (attempt === 2 && reaction !== void 0) {
1325
+ sections.push(`${tr("What just happened, and what you are reacting to:")}\n${reaction.map((entry) => said(entry, tr)).join("\n")}`);
1326
+ if (previous !== void 0) sections.push(tr("Your earlier intent did not work out: {intent}\nYou are trying again, knowing the above. Decide again what you do now.", { intent: previous.intent }));
1327
+ }
1328
+ return {
1329
+ persona: [
1330
+ describe(member.character, tr),
1331
+ request.text("roleplay/character-rules", { name: member.character.name }),
1332
+ request.text("roleplay/character-style", { name: member.character.name }),
1333
+ ...request.lookup ? [request.text("roleplay/character-lookup")] : [],
1334
+ request.text("roleplay/character-decide", {
1335
+ name: member.character.name,
1336
+ ...limitVariables(request.language ?? "en")
1337
+ })
1338
+ ].join("\n\n"),
1339
+ prompt: sections.join("\n\n")
1340
+ };
1341
+ } };
1342
+ /**
1343
+ * Whoever is with the player's character acts, unless the game master names who (it always does in play). While the world has places, a character that is in none
1344
+ * is not part of the scene: asking it to act is refused, so that someone the story never placed cannot answer from nowhere. (A character in
1345
+ * another place can be asked when the moment reaches it.)
1346
+ */
1347
+ const everyoneActs = { plan({ cast, requested }) {
1348
+ const placed = cast.some((member) => member.place !== void 0);
1349
+ const available = cast.filter((member) => member.character.control === "agent");
1350
+ const here = cast.find((member) => member.character.control === "player")?.place?.location.id;
1351
+ const inScene = (member) => !placed || member.place !== void 0;
1352
+ if (requested === void 0 || requested.length === 0) return available.filter((member) => placed && here !== void 0 ? member.place?.location.id === here : inScene(member)).map((member) => member.key);
1353
+ const unknown = requested.filter((key) => !available.some((member) => member.key === key));
1354
+ if (unknown.length > 0) throw new Error(`cannot activate ${unknown.join(", ")}: not a character that acts on its own (available: ${available.map((member) => member.key).join(", ")})`);
1355
+ const nowhere = [...new Set(requested)].map((key) => available.find((member) => member.key === key)).filter((member) => !inScene(member));
1356
+ if (nowhere.length > 0) throw new Error(`cannot activate ${nowhere.map((member) => member.key).join(", ")}: in no place, so not part of this scene. Only characters that have a place act (${available.filter(inScene).map((member) => member.key).join(", ") || "nobody"}); leave the others out`);
1357
+ return [...new Set(requested)];
1358
+ } };
1359
+ const acceptsAnyIntent = { validate: ({ intent }) => intent.trim() === "" ? {
1360
+ ok: false,
1361
+ reason: "the intent is empty"
1362
+ } : { ok: true } };
1363
+ /** A character whose intent failed and who is highly committed tries once more. */
1364
+ const persistentRetry = { select({ reports, outcomes }) {
1365
+ return reports.filter((report) => report.commitment === "high" && outcomes.some((outcome) => outcome.character === report.character && outcome.result === "failed")).map((report) => report.character);
1366
+ } };
1367
+ const acceptsAnyInput = { validate: () => ({ ok: true }) };
1368
+ /** The game master narrates. */
1369
+ const gameMasterNarrates = { narrate: () => Promise.resolve(void 0) };
1370
+ /** Compares what was said, ignoring the quotes around it and the way whitespace is laid out. */
1371
+ function sameWords(a, b) {
1372
+ const plain = (text) => trimCharacters(text.trim(), "\"“”„«»'‘’").replace(/\s+/g, " ").trim();
1373
+ return plain(a) === plain(b);
1374
+ }
1375
+ /** How many earlier events the game master is reminded of at most. */
1376
+ const REMINDED_EVENTS = 5;
1377
+ /**
1378
+ * The state of the scene, what is still open in the story, and the earlier events that the
1379
+ * player's move brings to mind (by the session's search of words and meaning, and by who is named):
1380
+ * those already folded out of the conversation into the summaries, whose detail the summaries may have lost.
1381
+ */
1382
+ /** Where the player is and what is there, who is with them, and who is elsewhere. */
1383
+ function placedScene(cast, player, story, describeMember, tr, things) {
1384
+ const here = player?.place?.location;
1385
+ const sections = [];
1386
+ if (here !== void 0) {
1387
+ const view = {
1388
+ key: locationKey(here),
1389
+ location: here,
1390
+ here: cast.filter((member) => member.place?.location.id === here.id),
1391
+ ...things === void 0 ? {} : { items: things.at(here.id) },
1392
+ exits: story.locations.exitsFrom(here.id).flatMap((exit) => {
1393
+ const to = story.locations.get(exit.toId);
1394
+ return to === void 0 ? [] : [{
1395
+ key: locationKey(to),
1396
+ name: to.name,
1397
+ exit
1398
+ }];
1399
+ })
1400
+ };
1401
+ sections.push(tr("The player's character is in {place}", { place: describePlace(view, { withKeys: true }, tr).join("\n") }));
1402
+ sections.push(`${tr("Characters here:")}\n${view.here.map(describeMember).join("\n")}`);
1403
+ }
1404
+ const elsewhere = cast.filter((member) => member.place !== void 0 && member.place.location.id !== here?.id);
1405
+ if (elsewhere.length > 0) sections.push(`${tr("Characters elsewhere (they perceive nothing here unless the moment reaches them):")}\n${elsewhere.map((member) => tr("{member} - in {place} ({key})", {
1406
+ member: describeMember(member),
1407
+ place: member.place.location.name,
1408
+ key: locationKey(member.place.location)
1409
+ })).join("\n")}`);
1410
+ const nowhere = cast.filter((member) => member.place === void 0);
1411
+ if (nowhere.length > 0) sections.push(`${tr("Characters with no place (not part of this scene; they cannot be asked to act):")}\n${nowhere.map(describeMember).join("\n")}`);
1412
+ return sections.join("\n\n");
1413
+ }
1414
+ const castSummary = { scene({ tracked, time, world, cast, turn, input, queryVector, story, items, language: code, report }) {
1415
+ const language = languageOf$1(code);
1416
+ const tr = translator(language);
1417
+ const join = (entries) => entries.join(tr("; "));
1418
+ const describeMember = (member) => {
1419
+ const { key, character, state } = member;
1420
+ const role = character.control === "player" ? tr("the player's character, \"{key}\"", { key }) : tr("acts through \"{key}\"", { key });
1421
+ const seen = [state?.publicState, state?.activity].filter((text) => text !== void 0 && text.trim() !== "");
1422
+ const where = whereIs(member, tr);
1423
+ return `- ${referent(character)} (${role})${where === "" ? "" : ` [${where}]`}${character.summary === "" ? "" : `${tr(": ")}${character.summary}`}${seen.length > 0 ? ` ${tr("Currently: {state}", { state: join(seen) })}` : ""}`;
1424
+ };
1425
+ const player = cast.find((member) => member.character.control === "player");
1426
+ const days = time?.agenda === void 0 ? "" : describeSceneAgenda(time.agenda, time.now.now, tr, language);
1427
+ const scene = cast.some((member) => member.place !== void 0) ? placedScene(cast, player, story, describeMember, tr, items) : cast.map(describeMember).join("\n");
1428
+ const parts = [];
1429
+ const add = (id, text) => {
1430
+ parts.push(text);
1431
+ report?.section(id, text);
1432
+ };
1433
+ if (time !== void 0) add("time", timeNotice(time, language, tr));
1434
+ if (days !== "") add("agenda", days);
1435
+ add("scene", `${tr("Scene before turn {turn}:", { turn })}\n${scene}`);
1436
+ const activation = describeActivationCandidates(cast, input, story, tr);
1437
+ if (activation !== "") add("activation", activation);
1438
+ if (items !== void 0) {
1439
+ const carried = cast.flatMap((member) => {
1440
+ const mine = items.carried(member.character.id);
1441
+ return mine.length === 0 ? [] : [`- ${member.character.name} (${member.key}): ${describeItems(mine, { withKeys: true }, tr)}`];
1442
+ });
1443
+ if (carried.length > 0) add("carried", `${tr("What characters have on them:")}\n${carried.join("\n")}`);
1444
+ }
1445
+ if (world !== void 0 && world.happened.length > 0) add("world", `${tr("The world acted since the last turn, by itself:")}\n${world.happened.map((line) => `- ${line}`).join("\n")}`);
1446
+ if (world?.upcoming !== void 0 && world.upcoming.length > 0) add("upcoming", `${tr("Known beforehand, still to come (who knows of it; it will happen by itself when its time comes):")}\n${world.upcoming.map((entry) => `- ${entry.text}${entry.when === void 0 ? "" : ` (${entry.when})`} ${tr("[known to {who}]", { who: entry.who })}`).join("\n")}`);
1447
+ if (world !== void 0 && world.beats.length > 0) add("beats", `${tr("Weave these into the story when it fits, then say you did with addressed in narrate (each stays for a few turns and is then let go):")}\n${world.beats.map((beat) => `- [${beat.id}] ${beat.text}`).join("\n")}`);
1448
+ if (tracked !== void 0 && tracked.length > 0) add("tracked", `${tr("What the story keeps track of (change it with variable_changes in an outcome when what happened calls for it):")}\n${tracked.map((line) => `- ${line}`).join("\n")}`);
1449
+ const threads = story.threads.list("open");
1450
+ if (threads.length > 0) add("threads", `${tr("Still open in the story:")}\n${threads.map((thread) => `- ${thread.text}`).join("\n")}`);
1451
+ const folded = story.summaries.list().reduce((latest, summary) => Math.max(latest, summary.toTurn), 0);
1452
+ if (folded > 0) {
1453
+ const mentionedIds = mentioned(input, cast.map(({ character }) => character));
1454
+ const cues = tokens(input);
1455
+ const names = new Map(cast.map(({ character }) => [character.id, character.name]));
1456
+ const byMeaning = story.searchEvents({
1457
+ text: input,
1458
+ ...queryVector === void 0 ? {} : { vector: queryVector },
1459
+ toTurn: folded,
1460
+ limit: 10
1461
+ });
1462
+ const byCues = story.events.list({ toTurn: folded }).filter((event) => !byMeaning.some((found) => found.id === event.id)).map((event) => ({
1463
+ event,
1464
+ score: 3 * event.involves.filter((id) => mentionedIds.has(id)).length + overlap(cues, event.text, event.tags)
1465
+ })).filter(({ score }) => score >= 2).sort((a, b) => b.score + .5 * b.event.importance - a.score - .5 * a.event.importance || b.event.turn - a.event.turn).map(({ event }) => event);
1466
+ const ranked = [...byMeaning.map((event) => ({
1467
+ event,
1468
+ how: "search"
1469
+ })), ...byCues.map((event) => ({
1470
+ event,
1471
+ how: "cues"
1472
+ }))];
1473
+ const chosen = ranked.slice(0, REMINDED_EVENTS).sort((a, b) => a.event.turn - b.event.turn);
1474
+ const relevant = chosen.map(({ event }) => ({ event }));
1475
+ report?.selected({
1476
+ events: chosen.map(({ event, how }) => ({
1477
+ turn: event.turn,
1478
+ text: event.text,
1479
+ how
1480
+ })),
1481
+ omitted: ranked.length - chosen.length,
1482
+ folded
1483
+ });
1484
+ if (relevant.length > 0) add("events", `${tr("Earlier events that bear on what the player just did (from the records of the story):")}\n${relevant.map(({ event }) => {
1485
+ const who = event.involves.map((id) => names.get(id)).filter((name) => name !== void 0).join(tr(", "));
1486
+ return `- (${tr("turn {turn}", { turn: event.turn })}) ${event.text}${who === "" ? "" : ` [${who}]`}`;
1487
+ }).join("\n")}`);
1488
+ } else report?.selected({
1489
+ events: [],
1490
+ omitted: 0,
1491
+ folded: 0
1492
+ });
1493
+ return parts.join("\n\n");
1494
+ } };
1495
+ const sameCharacter = (utterance, character) => utterance.character === character || utterance.name === character;
1496
+ /** Every utterance appears once, exactly as given and in the order spoken, and no one speaks who did not. */
1497
+ const exactUtterances = {
1498
+ check(segments, required) {
1499
+ const problems = [];
1500
+ const used = /* @__PURE__ */ new Set();
1501
+ let latest = 0;
1502
+ segments.forEach((segment, index) => {
1503
+ const at = `segment ${index + 1}`;
1504
+ if (segment.type === "narration") {
1505
+ if (segment.text.trim() === "") problems.push(`${at}: the narration is empty`);
1506
+ return;
1507
+ }
1508
+ const own = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) ? [position] : []);
1509
+ const free = own.filter((position) => !used.has(position));
1510
+ const exact = free.find((position) => sameWords(segment.text, required[position].text));
1511
+ if (exact !== void 0) {
1512
+ used.add(exact);
1513
+ const spoken = required[exact];
1514
+ if (spoken.round < latest) problems.push(`${at}: the utterance of ${spoken.name} from round ${spoken.round} comes after one from a later round; utterances keep the order they were spoken in`);
1515
+ latest = Math.max(latest, spoken.round);
1516
+ } else if (free.length > 0) {
1517
+ used.add(free[0]);
1518
+ problems.push(`${at}: the utterance of ${required[free[0]].name} was changed; it must be exactly "${required[free[0]].text}"`);
1519
+ } else if (own.length > 0) problems.push(`${at}: ${required[own[0]].name} has no more utterances to say; this one is repeated or invented, remove it`);
1520
+ else problems.push(`${at}: ${segment.character} has nothing to say this turn, so this utterance is invented; remove it`);
1521
+ });
1522
+ required.forEach((utterance, position) => {
1523
+ if (!used.has(position)) problems.push(`the utterance of ${utterance.name}${utterance.round > 1 ? ` (round ${utterance.round})` : ""} is missing; it must appear exactly as "${utterance.text}"`);
1524
+ });
1525
+ return problems;
1526
+ },
1527
+ repair(segments, required) {
1528
+ const used = /* @__PURE__ */ new Set();
1529
+ const kept = [];
1530
+ for (const segment of segments) {
1531
+ if (segment.type === "narration") {
1532
+ if (segment.text.trim() !== "") kept.push({
1533
+ segment,
1534
+ round: void 0
1535
+ });
1536
+ continue;
1537
+ }
1538
+ const free = required.flatMap((utterance, position) => sameCharacter(utterance, segment.character) && !used.has(position) ? [position] : []);
1539
+ const position = free.find((candidate) => sameWords(segment.text, required[candidate].text)) ?? free[0];
1540
+ if (position === void 0) continue;
1541
+ used.add(position);
1542
+ const spoken = required[position];
1543
+ kept.push({
1544
+ segment: {
1545
+ type: "utterance",
1546
+ character: spoken.character,
1547
+ name: spoken.name,
1548
+ text: spoken.text
1549
+ },
1550
+ round: spoken.round
1551
+ });
1552
+ }
1553
+ required.forEach((utterance, position) => {
1554
+ if (used.has(position)) return;
1555
+ const restored = {
1556
+ type: "utterance",
1557
+ character: utterance.character,
1558
+ name: utterance.name,
1559
+ text: utterance.text
1560
+ };
1561
+ const later = kept.findIndex((entry) => entry.round !== void 0 && entry.round > utterance.round);
1562
+ kept.splice(later < 0 ? kept.length : later, 0, {
1563
+ segment: restored,
1564
+ round: utterance.round
1565
+ });
1566
+ });
1567
+ return kept.map((entry) => entry.segment);
1568
+ }
1569
+ };
1570
+ /** What a character is reminded of is what the story's records bring back for it: by the cues of the moment, by its words, and by its meaning when vectors exist. */
1571
+ const recordsRecall = { recall: ({ member, situation, turn, policy, queryVector, explain, peek }, story, signal) => story.recallRanked({
1572
+ characterId: member.character.id,
1573
+ situation,
1574
+ turn,
1575
+ policy,
1576
+ ...explain === true ? { explain } : {},
1577
+ ...member.place === void 0 ? {} : { locationId: member.place.location.id }
1578
+ }, signal, {
1579
+ ...queryVector === void 0 ? {} : { queryVector },
1580
+ ...peek === true ? { peek } : {}
1581
+ }) };
1582
+ /**
1583
+ * Writes no memory. What the game master decided about each character is applied when the round is
1584
+ * recorded, so without a memory keeper the story keeps its states and no events.
1585
+ */
1586
+ const writesNothing = { commit: () => Promise.resolve({
1587
+ writes: 0,
1588
+ notes: ""
1589
+ }) };
1590
+ /** Makes up nothing, and has nothing to fit in: without a world author the world stays as it was written. */
1591
+ const declinesToAuthor = {
1592
+ create: () => Promise.resolve({
1593
+ created: [],
1594
+ declined: "no world author is installed, so the world cannot grow"
1595
+ }),
1596
+ consolidate: () => Promise.resolve({
1597
+ resolved: 0,
1598
+ notes: ""
1599
+ })
1600
+ };
1601
+ /** Lets no organisation act: without a strategist factions change only through what the story records. */
1602
+ const factionsStayPut = { strategize: () => Promise.resolve({ acted: [] }) };
1603
+ /** Reflects on nothing: without a reflector what characters believe changes only through what the story records. */
1604
+ const reflectsOnNothing = { reflect: () => Promise.resolve({ characters: [] }) };
1605
+ /** Finds no fault: without a gate the output is delivered as the game master wrote it. */
1606
+ const tracksNothing = { track: () => Promise.resolve(0) };
1607
+ const keepsNoErrands = { keep: () => Promise.resolve(0) };
1608
+ const passesEverything = { check: () => Promise.resolve([]) };
1609
+ /** Finds no broken rule: without a check the game master's judgement of an action stands as it is. */
1610
+ const breaksNoRule = { check: () => Promise.resolve([]) };
1611
+ /** Judges nothing: without a judge a trigger that waits on a statement never sees it hold. */
1612
+ const judgesNothing = { judge: () => Promise.resolve({ judged: 0 }) };
1613
+ /** Offers nothing: without a suggester the player writes their own move. */
1614
+ const offersNothing = { suggest: () => Promise.resolve([]) };
1615
+ function defaultBoundaries() {
1616
+ return {
1617
+ planner: everyoneActs,
1618
+ characterContext: sharedContext,
1619
+ outputValidator: acceptsAnyIntent,
1620
+ retryPolicy: persistentRetry,
1621
+ inputValidator: acceptsAnyInput,
1622
+ narrator: gameMasterNarrates,
1623
+ narrationChecker: exactUtterances,
1624
+ committer: writesNothing,
1625
+ author: declinesToAuthor,
1626
+ strategist: factionsStayPut,
1627
+ reflector: reflectsOnNothing,
1628
+ judge: judgesNothing,
1629
+ outputGate: passesEverything,
1630
+ ruleCheck: breaksNoRule,
1631
+ variableTracker: tracksNothing,
1632
+ errandKeeper: keepsNoErrands,
1633
+ suggester: offersNothing,
1634
+ recaller: recordsRecall,
1635
+ sceneContext: castSummary
1636
+ };
1637
+ }
1028
1638
  // src/host/orchestration/observation.ts
1029
1639
  /** 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. */
1030
1640
  function observeSurroundings(session, characterId, turn) {
@@ -1058,10 +1668,11 @@ function observeAsPlayer(session, turn) {
1058
1668
  const NOTE_KINDS = [
1059
1669
  "suggestions",
1060
1670
  "away",
1061
- "world"
1671
+ "world",
1672
+ "message"
1062
1673
  ];
1063
1674
  // src/host/sessions/notes.ts
1064
- const KEY$4 = "notes";
1675
+ const KEY$5 = "notes";
1065
1676
  const isNote = (value) => {
1066
1677
  if (typeof value !== "object" || value === null) return false;
1067
1678
  const note = value;
@@ -1069,12 +1680,12 @@ const isNote = (value) => {
1069
1680
  };
1070
1681
  /** The notes of a session, at most one per kind. */
1071
1682
  function readNotes(session) {
1072
- const stored = session.metadata.getValue(KEY$4);
1683
+ const stored = session.metadata.getValue(KEY$5);
1073
1684
  return Array.isArray(stored) ? stored.filter(isNote) : [];
1074
1685
  }
1075
1686
  /** Replaces the note of the same kind. */
1076
1687
  function putNote(session, note) {
1077
- session.metadata.setValue(KEY$4, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1688
+ session.metadata.setValue(KEY$5, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1078
1689
  }
1079
1690
  /** The most lines one note keeps: what is past it is not told. */
1080
1691
  const MAX_NOTE_LINES = 8;
@@ -1089,7 +1700,7 @@ function addToNote(session, kind, turn, lines) {
1089
1700
  }
1090
1701
  /** Removes every note: they belong to the turn that made them. */
1091
1702
  function clearNotes(session) {
1092
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$4, []);
1703
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$5, []);
1093
1704
  }
1094
1705
  /**
1095
1706
  * The notes of a session, for the player's screen.
@@ -1150,10 +1761,10 @@ function masterTrace(events) {
1150
1761
  };
1151
1762
  }
1152
1763
  // src/host/triggers/deliver.ts
1153
- const KEY$3 = "triggers.withdrawn";
1764
+ const KEY$4 = "triggers.withdrawn";
1154
1765
  /** Why a note was withdrawn instead of told, by the number of the note. */
1155
1766
  function readWithdrawn(session) {
1156
- const stored = session.metadata.getValue(KEY$3);
1767
+ const stored = session.metadata.getValue(KEY$4);
1157
1768
  if (!Array.isArray(stored)) return {};
1158
1769
  return Object.fromEntries(stored.flatMap((entry) => {
1159
1770
  const { note, reason } = entry ?? {};
@@ -1172,7 +1783,7 @@ function deliverNow(session, notes, clock) {
1172
1783
  note: Number(note),
1173
1784
  reason
1174
1785
  }));
1175
- session.metadata.setValue(KEY$3, [...before, ...withdrawn.map(({ note, reason }) => ({
1786
+ session.metadata.setValue(KEY$4, [...before, ...withdrawn.map(({ note, reason }) => ({
1176
1787
  note: note.id,
1177
1788
  reason
1178
1789
  }))].slice(-100));
@@ -1183,9 +1794,9 @@ function deliverNow(session, notes, clock) {
1183
1794
  }));
1184
1795
  }
1185
1796
  // src/host/triggers/judged.ts
1186
- const KEY$2 = "triggers.judged";
1797
+ const KEY$3 = "triggers.judged";
1187
1798
  function readVerdicts(session) {
1188
- const stored = session.metadata.getValue(KEY$2);
1799
+ const stored = session.metadata.getValue(KEY$3);
1189
1800
  if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
1190
1801
  const verdicts = {};
1191
1802
  for (const [statement, value] of Object.entries(stored)) {
@@ -1199,7 +1810,7 @@ function readVerdicts(session) {
1199
1810
  }
1200
1811
  /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
1201
1812
  function writeVerdicts(session, verdicts, keep) {
1202
- session.metadata.setValue(KEY$2, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1813
+ session.metadata.setValue(KEY$3, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1203
1814
  }
1204
1815
  /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
1205
1816
  const verdictReader = (session) => {
@@ -1333,11 +1944,11 @@ function noteStore(session, settings, clock) {
1333
1944
  };
1334
1945
  }
1335
1946
  // src/host/sessions/trace.ts
1336
- const KEY$1 = "trace";
1947
+ const KEY$2 = "trace";
1337
1948
  const isTrace = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.startedAt === "number";
1338
1949
  /** What the story kept of each turn's work, oldest first. It belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1339
1950
  function readTraces(session) {
1340
- const stored = session.metadata.getValue(KEY$1);
1951
+ const stored = session.metadata.getValue(KEY$2);
1341
1952
  return Array.isArray(stored) ? stored.filter(isTrace) : [];
1342
1953
  }
1343
1954
  /** Adds to a turn's trace what one source of it knows; the sources (the characters' briefs, the scene, the log at the end of the turn) arrive at different times. */
@@ -1356,10 +1967,10 @@ function updateTrace(session, turn, patch, merge) {
1356
1967
  if (at === -1) all.push(next);
1357
1968
  else all[at] = next;
1358
1969
  all.sort((a, b) => a.turn - b.turn);
1359
- session.metadata.setValue(KEY$1, all.slice(-30));
1970
+ session.metadata.setValue(KEY$2, all.slice(-30));
1360
1971
  }
1361
1972
  // src/host/sessions/activity.ts
1362
- const KEY = "activity";
1973
+ const KEY$1 = "activity";
1363
1974
  const isEntry = (value) => {
1364
1975
  if (typeof value !== "object" || value === null) return false;
1365
1976
  const entry = value;
@@ -1367,13 +1978,13 @@ const isEntry = (value) => {
1367
1978
  };
1368
1979
  /** The recorded runs, oldest first. */
1369
1980
  function readActivity(session) {
1370
- const stored = session.metadata.getValue(KEY);
1981
+ const stored = session.metadata.getValue(KEY$1);
1371
1982
  return Array.isArray(stored) ? stored.filter(isEntry) : [];
1372
1983
  }
1373
1984
  /** Files the run and returns the runs that fell off the end of the record to make room. */
1374
1985
  function recordActivity(session, entry) {
1375
1986
  const all = [...readActivity(session), entry];
1376
- session.metadata.setValue(KEY, all.slice(-60));
1987
+ session.metadata.setValue(KEY$1, all.slice(-60));
1377
1988
  return all.slice(0, -60);
1378
1989
  }
1379
1990
  const RUN_FOLDER = "activity";
@@ -1455,11 +2066,76 @@ function recordDecisions(folder, site, report, now = () => /* @__PURE__ */ new D
1455
2066
  writeFileSync(aside, JSON.stringify(stats, null, 2));
1456
2067
  renameSync(aside, target);
1457
2068
  }
2069
+ // src/host/sessions/autonomy.ts
2070
+ const KEY = "autonomy";
2071
+ const isMessage = (value) => {
2072
+ const entry = value;
2073
+ return typeof entry === "object" && entry !== null && typeof entry["at"] === "number" && typeof entry["character"] === "string" && typeof entry["name"] === "string" && typeof entry["text"] === "string";
2074
+ };
2075
+ function readAutonomy(session) {
2076
+ const stored = session.metadata.getValue(KEY);
2077
+ const sent = typeof stored?.sent === "object" && stored.sent !== null && !Array.isArray(stored.sent) ? Object.fromEntries(Object.entries(stored.sent).filter(([, value]) => typeof value === "number")) : {};
2078
+ return {
2079
+ unanswered: typeof stored?.unanswered === "number" ? stored.unanswered : 0,
2080
+ sent,
2081
+ inbox: Array.isArray(stored?.inbox) ? stored.inbox.filter(isMessage) : []
2082
+ };
2083
+ }
2084
+ /** A character wrote to the player: it counts as one more thing done without a reply, and waits to be told to the story. */
2085
+ function recordMessage(session, message) {
2086
+ const state = readAutonomy(session);
2087
+ const next = {
2088
+ unanswered: state.unanswered + 1,
2089
+ sent: {
2090
+ ...state.sent,
2091
+ [message.character]: message.at
2092
+ },
2093
+ inbox: [...state.inbox, message].slice(-20)
2094
+ };
2095
+ session.metadata.setValue(KEY, next);
2096
+ return next;
2097
+ }
2098
+ /** A character was asked whether it wants to write and did not: it is not asked again until the gap has passed. */
2099
+ function recordAsk(session, character, at) {
2100
+ const state = readAutonomy(session);
2101
+ session.metadata.setValue(KEY, {
2102
+ ...state,
2103
+ sent: {
2104
+ ...state.sent,
2105
+ [character]: at
2106
+ }
2107
+ });
2108
+ }
2109
+ /** The player wrote: what the story was not told of yet, and the count of things done without a reply starts again. */
2110
+ function takeInbox(session) {
2111
+ const state = readAutonomy(session);
2112
+ if (state.inbox.length === 0 && state.unanswered === 0) return [];
2113
+ session.metadata.setValue(KEY, {
2114
+ ...state,
2115
+ unanswered: 0,
2116
+ inbox: []
2117
+ });
2118
+ return state.inbox;
2119
+ }
2120
+ /** When the player last played: the last turn, or the start of a story not yet played. */
2121
+ function lastPlayerAt(session) {
2122
+ const { lastPlayedAt, createdAt } = session.metadata.get();
2123
+ const at = Date.parse(lastPlayedAt ?? createdAt);
2124
+ return Number.isNaN(at) ? void 0 : at;
2125
+ }
1458
2126
  // src/host/clock/agenda.ts
1459
2127
  const CURSOR = "agenda.cursor";
1460
2128
  const ASKED = "agenda.asked";
1461
2129
  /** Characters on their way to the place their day has them at, by character id: they get there when the way has taken as long as it takes. */
1462
2130
  const TRAVEL = "agenda.travel";
2131
+ /** The characters whose day changed since the autonomy last looked, by key: what makes a character likelier to write to the player (work is over, it woke up). */
2132
+ const SHIFTED = "agenda.shifted";
2133
+ /** Characters whose day has given way to what the story made of them, by character id: the routine does not pull them until `until`, when they rejoin it. */
2134
+ const HOLDS = "agenda.holds";
2135
+ /** The longest a character stays where the story left it waiting for the player. */
2136
+ const PLAYER_HOLD_CAP = 1440 * MINUTE;
2137
+ /** How long a character that no window bounds is held when nothing says. */
2138
+ const DEFAULT_HOLD = 60 * MINUTE;
1463
2139
  /** At most this many characters are asked to be given a day at a time, so that it never floods the world author. */
1464
2140
  const MAX_ASKED = 3;
1465
2141
  /** How far ahead the characters are told about what comes next in their day. */
@@ -1467,6 +2143,65 @@ const NEXT_HORIZON = 240 * MINUTE;
1467
2143
  /** What a character is shown of its own agenda at most. */
1468
2144
  const SHOWN_ENGAGEMENTS = 4;
1469
2145
  const SHOWN_GOALS = 3;
2146
+ const readHolds = (session) => {
2147
+ const stored = session.metadata.getValue(HOLDS);
2148
+ return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
2149
+ };
2150
+ /** Whether the story has taken a character off its day for now. */
2151
+ function isHeld(session, characterId, now) {
2152
+ const hold = readHolds(session)[characterId];
2153
+ return hold !== void 0 && now < hold.until;
2154
+ }
2155
+ /**
2156
+ * Take a character off its day: what the story made of it (it was led elsewhere, woken, sent on an errand) outranks the routine. The routine does not pull it back before
2157
+ * `minutes` are over, or when that is not said before its day next changes, and it takes its day up again then.
2158
+ */
2159
+ function holdCharacter(session, characterId, zone, now, minutes, untilPlayer = false) {
2160
+ const windows = session.routines.list(characterId);
2161
+ const current = occurrenceAt(windows, now, zone);
2162
+ const next = current === void 0 ? nextOccurrence(windows, now, zone, 1440 * MINUTE) : void 0;
2163
+ const until = untilPlayer ? now + PLAYER_HOLD_CAP : minutes !== void 0 ? now + minutes * MINUTE : current?.endsAt ?? next?.startsAt ?? now + DEFAULT_HOLD;
2164
+ const holds = readHolds(session);
2165
+ const kept = holds[characterId];
2166
+ const live = kept !== void 0 && now < kept.until;
2167
+ const end = Math.max(until, live ? kept.until : -Infinity, now + MINUTE);
2168
+ const waiting = untilPlayer || live && kept.untilPlayer !== void 0;
2169
+ holds[characterId] = {
2170
+ since: live ? kept.since : now,
2171
+ until: end,
2172
+ ...waiting ? { untilPlayer: live && kept.untilPlayer !== void 0 ? kept.untilPlayer : { apart: false } } : {}
2173
+ };
2174
+ session.metadata.setValue(HOLDS, holds);
2175
+ const stored = session.metadata.getValue(TRAVEL);
2176
+ if (typeof stored === "object" && stored !== null && !Array.isArray(stored) && String(characterId) in stored) {
2177
+ const { [String(characterId)]: _gone, ...rest } = stored;
2178
+ session.metadata.setValue(TRAVEL, rest);
2179
+ }
2180
+ return end;
2181
+ }
2182
+ /** Whether a character is asleep now: its day has it asleep, in the place it sleeps in, and nothing has woken it. The player's character is never asleep: it is the player's. */
2183
+ function sleepingNow(session, characterId, zone, now) {
2184
+ const character = session.characters.get(characterId);
2185
+ if (character === void 0 || character.control === "player" || isHeld(session, characterId, now)) return void 0;
2186
+ const current = occurrenceAt(session.routines.list(characterId), now, zone);
2187
+ if (current?.window.sleep !== true) return void 0;
2188
+ const here = session.placements.get("character", characterId);
2189
+ if (current.window.locationId !== void 0 && here?.locationId !== current.window.locationId) return void 0;
2190
+ return { until: current.endsAt };
2191
+ }
2192
+ /** Everyone asleep now. */
2193
+ function sleepersNow(session, zone, now) {
2194
+ return session.characters.list().flatMap((character) => {
2195
+ const asleep = sleepingNow(session, character.id, zone, now);
2196
+ return asleep === void 0 ? [] : [{
2197
+ character: character.id,
2198
+ key: keyOfCharacter$1(character),
2199
+ name: character.name,
2200
+ aliases: character.aliases,
2201
+ until: asleep.until
2202
+ }];
2203
+ });
2204
+ }
1470
2205
  const keyOfCharacter$1 = (character) => character.sourceId ?? String(character.id);
1471
2206
  /**
1472
2207
  * Bring the days of the characters up to the story's time: those who are not in the player's scene go where their
@@ -1481,9 +2216,11 @@ function catchUpRoutines(session, zone, now, turn, ask) {
1481
2216
  const player = session.characters.list().find((character) => character.control === "player");
1482
2217
  const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1483
2218
  const moves = [];
2219
+ const shifted = /* @__PURE__ */ new Set();
1484
2220
  const stored = session.metadata.getValue(TRAVEL);
1485
2221
  const journeys = typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
1486
2222
  const arrive = (character, target) => {
2223
+ if (cursor !== void 0) shifted.add(keyOfCharacter$1(character));
1487
2224
  if (target.locationId !== void 0) {
1488
2225
  session.move(character.id, {
1489
2226
  to: target.locationId,
@@ -1500,6 +2237,7 @@ function catchUpRoutines(session, zone, now, turn, ask) {
1500
2237
  }
1501
2238
  if (session.characterStates.get(character.id)?.activity !== target.activity) session.characterStates.update(character.id, { activity: target.activity });
1502
2239
  };
2240
+ const holds = readHolds(session);
1503
2241
  const alreadyAsked = new Set(Array.isArray(session.metadata.getValue(ASKED)) ? session.metadata.getValue(ASKED) : []);
1504
2242
  const asked = [];
1505
2243
  for (const character of session.characters.list()) {
@@ -1520,6 +2258,18 @@ function catchUpRoutines(session, zone, now, turn, ask) {
1520
2258
  }
1521
2259
  continue;
1522
2260
  }
2261
+ const held = holds[characterId];
2262
+ let rejoin = false;
2263
+ if (held !== void 0) {
2264
+ if (held.untilPlayer !== void 0 && now < held.until) {
2265
+ if (away) held.untilPlayer.apart = true;
2266
+ else if (held.untilPlayer.apart) delete holds[characterId];
2267
+ continue;
2268
+ }
2269
+ if (now < held.until) continue;
2270
+ delete holds[characterId];
2271
+ rejoin = true;
2272
+ }
1523
2273
  if (!away) continue;
1524
2274
  const current = occurrenceAt(window, now, zone);
1525
2275
  const journey = journeys[characterId];
@@ -1534,7 +2284,7 @@ function catchUpRoutines(session, zone, now, turn, ask) {
1534
2284
  }
1535
2285
  if (current === void 0) continue;
1536
2286
  const before = cursor === void 0 ? void 0 : occurrenceAt(window, cursor, zone);
1537
- if (before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
2287
+ if (!rejoin && before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
1538
2288
  const target = current.window;
1539
2289
  if (target.locationId !== void 0 && (here?.locationId !== target.locationId || target.position !== void 0 && here.position !== target.position)) {
1540
2290
  const way = here?.locationId === target.locationId ? void 0 : session.planMove(characterId, { to: target.locationId });
@@ -1550,32 +2300,52 @@ function catchUpRoutines(session, zone, now, turn, ask) {
1550
2300
  continue;
1551
2301
  }
1552
2302
  arrive(character, target);
1553
- } else if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
2303
+ } else {
2304
+ if (cursor !== void 0) shifted.add(keyOfCharacter$1(character));
2305
+ if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
2306
+ }
1554
2307
  }
1555
2308
  session.metadata.setValue(CURSOR, now);
1556
2309
  session.metadata.setValue(TRAVEL, journeys);
2310
+ session.metadata.setValue(HOLDS, holds);
2311
+ if (shifted.size > 0) {
2312
+ const before = session.metadata.getValue(SHIFTED);
2313
+ session.metadata.setValue(SHIFTED, [.../* @__PURE__ */ new Set([...Array.isArray(before) ? before.filter((entry) => typeof entry === "string") : [], ...shifted])]);
2314
+ }
1557
2315
  if (asked.length > 0) session.metadata.setValue(ASKED, [...alreadyAsked, ...asked]);
1558
2316
  return moves;
1559
2317
  });
1560
2318
  }
2319
+ /** The characters whose day changed since this was last asked, by key; asking forgets them. */
2320
+ function takeShifts(session) {
2321
+ const stored = session.metadata.getValue(SHIFTED);
2322
+ const keys = Array.isArray(stored) ? stored.filter((entry) => typeof entry === "string") : [];
2323
+ if (keys.length > 0) session.metadata.setValue(SHIFTED, []);
2324
+ return keys;
2325
+ }
1561
2326
  /** A character's agenda at an instant, with places by name and others by name. */
1562
- function agendaView(session, characterId, zone, now) {
2327
+ function agendaView(session, characterId, zone, now, scheduled = true) {
1563
2328
  const agenda = agendaAt(session, characterId, now, zone, {
1564
2329
  horizon: NEXT_HORIZON,
1565
2330
  engagements: SHOWN_ENGAGEMENTS,
1566
2331
  goals: SHOWN_GOALS
1567
2332
  });
2333
+ const hold = scheduled ? readHolds(session)[characterId] : void 0;
2334
+ const held = hold !== void 0 && now < hold.until;
2335
+ const dayless = !scheduled || session.characters.get(characterId)?.control === "player";
1568
2336
  const place = (id) => id === void 0 ? void 0 : session.locations.get(id)?.name;
1569
2337
  const names = (ids) => ids.filter((id) => id !== characterId).map((id) => session.characters.get(id)?.name ?? String(id));
1570
2338
  return {
1571
2339
  zone,
1572
- ...agenda.now === void 0 ? {} : { now: {
2340
+ ...agenda.now === void 0 || held || dayless ? {} : { now: {
1573
2341
  activity: agenda.now.window.activity,
1574
2342
  ...place(agenda.now.window.locationId) === void 0 ? {} : { place: place(agenda.now.window.locationId) },
1575
2343
  until: agenda.now.endsAt,
1576
- interruptible: agenda.now.window.interruptible
2344
+ interruptible: agenda.now.window.interruptible,
2345
+ ...agenda.now.window.sleep === true ? { sleep: true } : {}
1577
2346
  } },
1578
- ...agenda.next === void 0 ? {} : { next: {
2347
+ ...held ? { offDay: { until: hold.until } } : {},
2348
+ ...agenda.next === void 0 || dayless ? {} : { next: {
1579
2349
  activity: agenda.next.window.activity,
1580
2350
  ...place(agenda.next.window.locationId) === void 0 ? {} : { place: place(agenda.next.window.locationId) },
1581
2351
  at: agenda.next.startsAt
@@ -1602,12 +2372,13 @@ const SOON = 30 * MINUTE;
1602
2372
  const MAX_NOTES = 6;
1603
2373
  /** An engagement that has been overdue for longer than this is not worth the game master's attention every turn. */
1604
2374
  const STALE = 1440 * MINUTE;
1605
- function sceneAgenda(session, zone, now, moved) {
2375
+ function sceneAgenda(session, zone, now, moved, scheduled = true) {
1606
2376
  const player = session.characters.list().find((character) => character.control === "player");
1607
2377
  const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1608
2378
  const withPlayer = new Set(session.characters.list().filter((character) => playerPlace !== void 0 && session.placements.get("character", character.id)?.locationId === playerPlace && character.control !== "player").map((character) => character.id));
1609
2379
  const here = [];
1610
- for (const characterId of withPlayer) {
2380
+ for (const characterId of scheduled ? withPlayer : []) {
2381
+ if (isHeld(session, characterId, now)) continue;
1611
2382
  const windows = session.routines.list(characterId);
1612
2383
  const current = occurrenceAt(windows, now, zone);
1613
2384
  const upcoming = nextOccurrence(windows, now, zone, SOON);
@@ -1636,43 +2407,49 @@ function sceneAgenda(session, zone, now, moved) {
1636
2407
  with: engagement.participants.map((id) => session.characters.get(id)?.name ?? String(id)),
1637
2408
  overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE)
1638
2409
  }));
2410
+ const asleep = scheduled ? sleepersNow(session, zone, now).map(({ key, name, until }) => ({
2411
+ key,
2412
+ name,
2413
+ until
2414
+ })) : [];
1639
2415
  return {
1640
2416
  zone,
1641
2417
  moved,
1642
2418
  here: here.slice(0, MAX_NOTES),
2419
+ asleep,
1643
2420
  engagements
1644
2421
  };
1645
2422
  }
1646
2423
  // src/host/clock/passage.ts
1647
2424
  /** The start of a turn: the time, how long the player was away, and what the days of the characters make of it. */
1648
- function startTurn(session, config, turn, wall) {
2425
+ function startTurn(session, config, turn, wall, scheduled = true) {
1649
2426
  const started = beginTurn(session, config, turn, wall);
1650
- const moved = catchUpRoutines(session, started.time.zone, started.time.now, turn, true);
2427
+ const moved = scheduled ? catchUpRoutines(session, started.time.zone, started.time.now, turn, true) : [];
1651
2428
  return {
1652
2429
  ...started,
1653
- agenda: sceneAgenda(session, started.time.zone, started.time.now, moved)
2430
+ agenda: sceneAgenda(session, started.time.zone, started.time.now, moved, scheduled)
1654
2431
  };
1655
2432
  }
1656
2433
  /** A round passes, and the characters outside the scene take up what their days have for the new time. */
1657
- function passRound(session, config, turn, round, wall, stated, minimum) {
2434
+ function passRound(session, config, turn, round, wall, stated, minimum, scheduled = true) {
1658
2435
  const span = endRound(session, config, turn, round, wall, stated, minimum);
1659
2436
  return {
1660
2437
  ...span,
1661
- moved: catchUpRoutines(session, span.zone, span.to, turn, false)
2438
+ moved: scheduled ? catchUpRoutines(session, span.zone, span.to, turn, false) : []
1662
2439
  };
1663
2440
  }
1664
2441
  /** Time is skipped, and the characters outside the scene take up what their days have for the new time. */
1665
- function skipAhead(session, config, turn, round, wall, request) {
2442
+ function skipAhead(session, config, turn, round, wall, request, scheduled = true) {
1666
2443
  const span = skipTime(session, config, turn, round, wall, request);
1667
2444
  return {
1668
2445
  ...span,
1669
- moved: catchUpRoutines(session, span.zone, span.to, turn, true)
2446
+ moved: scheduled ? catchUpRoutines(session, span.zone, span.to, turn, true) : []
1670
2447
  };
1671
2448
  }
1672
2449
  /** What a character is told of its own agenda. */
1673
- function agendaFor(session, config, turn, wall, characterId) {
2450
+ function agendaFor(session, config, turn, wall, characterId, scheduled = true) {
1674
2451
  const time = readTime(session, config, turn, wall());
1675
- return agendaView(session, characterId, zoneOf(config), time.now);
2452
+ return agendaView(session, characterId, zoneOf(config), time.now, scheduled);
1676
2453
  }
1677
2454
  // src/host/clock/offscene.ts
1678
2455
  const HANDLED = "offscene.handled";
@@ -2087,9 +2864,11 @@ function checkMove(session, characterKey, request) {
2087
2864
  ...request.position === void 0 ? {} : { position: request.position }
2088
2865
  } : {
2089
2866
  ok: false,
2090
- problems: planned.problems
2867
+ problems: planned.problems.map((problem) => /^the character does not know place /.test(problem) ? unknownPlace(to.name) : problem)
2091
2868
  };
2092
2869
  }
2870
+ /** What the game master is told when it sends a character somewhere it has not heard of (found live: the same refused call 38 times, because the reason named no way out). */
2871
+ const unknownPlace = (name) => `the character has not heard of ${name}, and a character only goes where it knows the way. Do not send it there: take it to a place it knows (get_character lists them), or let the story first make the place known to it (someone tells it, a sign, a map) and send it on a later turn`;
2093
2872
  function storeOf(session, folder, problem, queryVector, wall, prompt) {
2094
2873
  const settings = () => liveSettings(folder, problem);
2095
2874
  return {
@@ -2103,10 +2882,10 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
2103
2882
  time: (turn) => readTime(session, settings().clock, turn, wall()),
2104
2883
  beginTurn: (turn) => {
2105
2884
  observeAsPlayer(session, turn);
2106
- return startTurn(session, settings().clock, turn, wall());
2885
+ return startTurn(session, settings().clock, turn, wall(), settings().schedule.enabled);
2107
2886
  },
2108
- endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum),
2109
- skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request),
2887
+ endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum, settings().schedule.enabled),
2888
+ skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request, settings().schedule.enabled),
2110
2889
  checkVariableChanges: (changes) => changes.flatMap((spec) => {
2111
2890
  const planned = planVariableChange(session, spec);
2112
2891
  return planned.ok ? [] : planned.problems;
@@ -2165,15 +2944,66 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
2165
2944
  recordTrace: (turn, patch, merge) => {
2166
2945
  updateTrace(session, turn, patch, merge);
2167
2946
  },
2947
+ folders: async () => await storyRoots(dirname(dirname(folder)), folder),
2948
+ autonomy: {
2949
+ catchUp: (turn) => {
2950
+ if (!settings().schedule.enabled) return [];
2951
+ const { now, zone } = readTime(session, settings().clock, turn, wall());
2952
+ return catchUpRoutines(session, zone, now, turn, false);
2953
+ },
2954
+ shifts: () => takeShifts(session),
2955
+ state: () => readAutonomy(session),
2956
+ lastPlayerAt: () => lastPlayerAt(session),
2957
+ said: (turn, message) => {
2958
+ session.transaction(() => {
2959
+ recordMessage(session, message);
2960
+ addToNote(session, "message", turn, [`${message.name}: ${message.text}`]);
2961
+ });
2962
+ },
2963
+ asked: (character, at) => {
2964
+ recordAsk(session, character, at);
2965
+ },
2966
+ inbox: () => takeInbox(session),
2967
+ looked: (outcome, at) => {
2968
+ session.metadata.setValue("autonomy.look", {
2969
+ outcome,
2970
+ at
2971
+ });
2972
+ }
2973
+ },
2168
2974
  notes: () => readNotes(session),
2169
2975
  clearNotes: () => {
2170
2976
  clearNotes(session);
2171
2977
  },
2172
- agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId),
2173
- commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items }) => {
2978
+ agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId, settings().schedule.enabled),
2979
+ asleep: (turn, characterId) => {
2980
+ if (!settings().schedule.enabled) return void 0;
2981
+ const { now, zone } = readTime(session, settings().clock, turn, wall());
2982
+ return sleepingNow(session, characterId, zone, now);
2983
+ },
2984
+ sleepers: (turn) => {
2985
+ if (!settings().schedule.enabled) return [];
2986
+ const { now, zone } = readTime(session, settings().clock, turn, wall());
2987
+ return sleepersNow(session, zone, now).map(({ key, name, aliases, until }) => ({
2988
+ key,
2989
+ name,
2990
+ aliases,
2991
+ until
2992
+ }));
2993
+ },
2994
+ holdForPlayer: (characterId) => {
2995
+ if (!settings().schedule.enabled) return;
2996
+ const { now, zone } = readTime(session, settings().clock, session.metadata.get().turns + 1, wall());
2997
+ holdCharacter(session, characterId, zone, now, void 0, true);
2998
+ },
2999
+ commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items, hold }) => {
2174
3000
  session.characterStates.update(character, patch);
2175
3001
  const effects = (items ?? []).map((spec) => changeItem(session, character, spec));
2176
3002
  if (move !== void 0) session.move(character, move);
3003
+ if (hold !== void 0 && settings().schedule.enabled) {
3004
+ const { now, zone } = readTime(session, settings().clock, session.metadata.get().turns + 1, wall());
3005
+ holdCharacter(session, character, zone, now, hold.minutes, hold.untilPlayer === true);
3006
+ }
2177
3007
  return effects;
2178
3008
  })),
2179
3009
  checkItemChanges: (entries) => dryRunItems(session, entries),
@@ -2229,80 +3059,6 @@ function parseOoc(text) {
2229
3059
  }
2230
3060
  /** The longest answer to an out-of-character question. */
2231
3061
  const MAX_OOC_ANSWER = 1200;
2232
- // src/shared/roll.ts
2233
- /** The roll in a player's message, or nothing when the message does not start with `/roll`. The notation may be empty, and is then refused. */
2234
- function parseRoll(text) {
2235
- const value = text.trimStart();
2236
- if (value.slice(0, 5).toLowerCase() !== "/roll" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
2237
- const body = value.slice(5).trimStart();
2238
- const boundary = body.search(/\s/u);
2239
- return boundary < 0 ? {
2240
- expression: body,
2241
- reason: ""
2242
- } : {
2243
- expression: body.slice(0, boundary),
2244
- reason: body.slice(boundary).trim()
2245
- };
2246
- }
2247
- // src/shared/wait.ts
2248
- const UNITS = [
2249
- [/^(?:m|min|mins|minute|minutes|分钟|分)$/iu, 1],
2250
- [/^(?:h|hr|hrs|hour|hours|小时|時間|时)$/iu, 60],
2251
- [/^(?:d|day|days|天|日)$/iu, 1440]
2252
- ];
2253
- /**
2254
- * The wait in a player's message (`/wait 2 hours`, `/wait 30m until the ferry`, `/wait 3天`), or nothing when the message does not start with `/wait`. The time may be missing or
2255
- * unreadable, and is then `undefined` in `minutes`.
2256
- */
2257
- function parseWait(text) {
2258
- const value = text.trimStart();
2259
- if (value.slice(0, 5).toLowerCase() !== "/wait" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
2260
- const body = value.slice(5).trim();
2261
- const match = /^(\d+(?:\.\d+)?)\s*([\p{L}]+)\s*(.*)$/su.exec(body);
2262
- if (match === null) return {
2263
- minutes: void 0,
2264
- reason: body
2265
- };
2266
- const unit = UNITS.find(([pattern]) => pattern.test(match[2]));
2267
- if (unit === void 0) return {
2268
- minutes: void 0,
2269
- reason: body
2270
- };
2271
- const minutes = Math.round(Number(match[1]) * unit[1]);
2272
- return {
2273
- minutes: minutes >= 1 && minutes <= 525600 ? minutes : void 0,
2274
- reason: match[3].trim()
2275
- };
2276
- }
2277
- // src/host/agents/repeat-guard.ts
2278
- /**
2279
- * Keeps an agent that is stuck from making the same call again and again (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one
2280
- * refused round resolution): past `limit` identical calls in one turn the call is refused with a word that sends it on, and when it goes on regardless the turn is ended. The count starts over at the first step of every turn.
2281
- * @param languageOf the language of the chat the call belongs to, or nothing when the guard does not apply to it.
2282
- */
2283
- function guardRepeatedCalls(ctx, languageOf, limit) {
2284
- const calls = /* @__PURE__ */ new Map();
2285
- ctx.on("agent/pre-step", async (payload, next) => {
2286
- if (payload.step === 1) calls.delete(payload.agent.session.id);
2287
- return await next();
2288
- });
2289
- ctx.on("tools/pre-execute", async (exec, next) => {
2290
- const chat = exec.agent?.session.id;
2291
- const language = chat === void 0 || exec.agent?.session.header.origin === "subagent" ? void 0 : languageOf(exec);
2292
- if (chat === void 0 || language === void 0) return await next();
2293
- const signature = `${exec.name}:${JSON.stringify(exec.arguments)}`;
2294
- const seen = calls.get(chat) ?? /* @__PURE__ */ new Map();
2295
- calls.set(chat, seen);
2296
- const count = (seen.get(signature) ?? 0) + 1;
2297
- seen.set(signature, count);
2298
- if (count <= limit) return await next();
2299
- if (count > limit + 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
2300
- return {
2301
- kind: "deny",
2302
- reason: translator(languageOf$1(language))("This exact call was already made {count} times in this turn with the same result. Do not repeat it: go on with the next step, or finish and say what is left.", { count: count - 1 })
2303
- };
2304
- }, { prepend: true });
2305
- }
2306
3062
  // src/shared/tools.ts
2307
3063
  /** What this version can offer. A name in a settings file or a world that is not here is kept and ignored. */
2308
3064
  const OPTIONAL_TOOLS = [
@@ -2375,162 +3131,6 @@ function toolEnabled(board, agent, id) {
2375
3131
  function externalEnabled(board, agent, name) {
2376
3132
  return board[agent]?.[name] === true;
2377
3133
  }
2378
- // src/host/orchestration/character-runner.ts
2379
- /**
2380
- * Runs each character as a one-shot child of the game master. It is the character and nothing
2381
- * else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
2382
- * the memory of that character alone, so characters acting at the same time cannot see each
2383
- * other's memories.
2384
- */
2385
- function characterRunner(deps) {
2386
- return async (request, signal) => {
2387
- const brief = deps.boundaries().characterContext.brief(request);
2388
- const settings = deps.store.settings();
2389
- const tools = settings.memory.lookup ? createCharacterTools(() => ({
2390
- session: deps.store.story,
2391
- turn: request.turn,
2392
- policy: settings.memory,
2393
- queryVector: deps.store.queryVector
2394
- }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)).map((tool) => notingEmpty(tool, deps.store, request.turn, request.member.character.name)) : [];
2395
- const background = (request.knowledge?.lore.length ?? 0) > 0 && tools.some((tool) => tool.name === "recall_my_lore");
2396
- const external = externalGiven(deps.parent.ctx.tools, settings.tools, "characters");
2397
- const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
2398
- return parseCharacterAction(await runChild({
2399
- parent: deps.parent,
2400
- signal,
2401
- sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
2402
- ...childModel(settings, "characters", named),
2403
- trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named, request.away === true ? "off stage" : void 0),
2404
- reasoningEffort: deps.store.settings().reasoning.children,
2405
- persona: brief.persona,
2406
- prompt: brief.prompt,
2407
- tools,
2408
- external,
2409
- maxCalls: deps.store.settings().memory.lookupCalls + (external.length === 0 ? 0 : EXTERNAL_CALLS),
2410
- result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
2411
- unenforced: ["thought"],
2412
- beforeSubmit: submitGate(settings.prompts.language, background)
2413
- }));
2414
- };
2415
- }
2416
- /** A look-up that finds nothing is kept in the turn's trace: it is where the world lacks what a character reached for. */
2417
- function notingEmpty(tool, store, turn, character) {
2418
- return {
2419
- ...tool,
2420
- async execute(args, exec) {
2421
- const found = await tool.execute(args, exec);
2422
- const about = args.about;
2423
- if (Array.isArray(found) && found.length === 0 && typeof about === "string" && about.trim() !== "") try {
2424
- store.recordTrace?.(turn, {}, (current) => ({ missing: [...current.missing ?? [], {
2425
- character,
2426
- tool: tool.name,
2427
- about: about.trim().slice(0, 120)
2428
- }].slice(-40) }));
2429
- } catch {}
2430
- return found;
2431
- }
2432
- };
2433
- }
2434
- const BACKGROUND_CHECK = "before you answer: does this moment touch your own past, skills, training, secrets or what you know of a person or place? If it does, read that background first with recall_my_lore (about: the subject) and answer from it; if it does not, submit the same answer again unchanged";
2435
- /** The model decides whether the moment touches its background; asking once at the point of answering is what makes it decide. */
2436
- function submitGate(language, background) {
2437
- let asked = !background;
2438
- return (value) => {
2439
- if (!asked) {
2440
- asked = true;
2441
- return BACKGROUND_CHECK;
2442
- }
2443
- return spokenIn(language, value);
2444
- };
2445
- }
2446
- /** What a character that was given tools of other plugins may call on top of its memory look-ups. */
2447
- const EXTERNAL_CALLS = 5;
2448
- /** 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. */
2449
- function spokenIn(language, value) {
2450
- const given = value;
2451
- return wrongLanguage(language, {
2452
- thought: given.thought,
2453
- intent: given.intent,
2454
- utterance: given.utterance,
2455
- account: given.account
2456
- }, { strays: true }) ?? narratedSpeech(given.utterance);
2457
- }
2458
- const CLOSING_QUOTE = {
2459
- "\"": "\"",
2460
- "“": "”",
2461
- "「": "」",
2462
- "『": "』"
2463
- };
2464
- function outsideQuotedSpeech(utterance) {
2465
- const parts = [];
2466
- let outside = 0;
2467
- let cursor = 0;
2468
- while (cursor < utterance.length) {
2469
- const closing = CLOSING_QUOTE[utterance[cursor]];
2470
- if (closing === void 0) {
2471
- cursor += 1;
2472
- continue;
2473
- }
2474
- const end = utterance.indexOf(closing, cursor + 1);
2475
- if (end < 0) {
2476
- cursor += 1;
2477
- continue;
2478
- }
2479
- parts.push(utterance.slice(outside, cursor));
2480
- outside = end + 1;
2481
- cursor = outside;
2482
- }
2483
- parts.push(utterance.slice(outside));
2484
- return parts;
2485
- }
2486
- /** Writing instructions that ask for prose from the character's own point of view lead it to put its actions between its lines; the utterance is only what is said aloud. */
2487
- function narratedSpeech(utterance) {
2488
- if (utterance === void 0) return void 0;
2489
- const parts = outsideQuotedSpeech(utterance);
2490
- if (parts.length - 1 < 2) return void 0;
2491
- return parts.slice(1, -1).some((part) => part.replace(/[\s\p{P}]/gu, "").length >= 6) ? "the utterance holds more than the words said aloud: put what you do in intent and write in the utterance only what you say, with nothing between your lines" : void 0;
2492
- }
2493
- /** What the character was reminded of and why, for the run's record, when the recall said why. */
2494
- function recalledOf(request) {
2495
- const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
2496
- return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
2497
- clarity,
2498
- turn,
2499
- text,
2500
- why
2501
- })) };
2502
- }
2503
- const ANSWER_SCHEMA = {
2504
- type: "object",
2505
- properties: { answer: {
2506
- type: "string",
2507
- description: "The answer to the player, in plain words, in a few sentences."
2508
- } },
2509
- required: ["answer"],
2510
- additionalProperties: false
2511
- };
2512
- /**
2513
- * 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
2514
- * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
2515
- */
2516
- function answerRunner(deps) {
2517
- return async (request, signal) => {
2518
- const brief = deps.boundaries().characterContext.brief(request);
2519
- return (await runChild({
2520
- parent: deps.parent,
2521
- signal,
2522
- sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
2523
- ...childModel(deps.store.settings(), "records"),
2524
- trace: childTrace(deps.store, "records", "answer to the player"),
2525
- reasoningEffort: deps.store.settings().reasoning.children,
2526
- persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
2527
- prompt: brief.prompt,
2528
- tools: [],
2529
- maxCalls: 3,
2530
- result: ANSWER_SCHEMA
2531
- })).answer;
2532
- };
2533
- }
2534
3134
  // src/host/pacing/author.ts
2535
3135
  const RESULT = {
2536
3136
  type: "object",
@@ -2787,6 +3387,11 @@ function createTools$1(deps) {
2787
3387
  type: "string",
2788
3388
  required: true,
2789
3389
  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."
3390
+ },
3391
+ wakes: {
3392
+ type: "array",
3393
+ items: { type: "string" },
3394
+ description: "Keys of the characters asleep (the scene says who) that what the player did wakes: only those you list take part, and your narration must show them waking. A sleeper you do not list cannot be asked. Leave out when nobody is woken."
2790
3395
  }
2791
3396
  },
2792
3397
  output: {
@@ -2807,7 +3412,8 @@ function createTools$1(deps) {
2807
3412
  });
2808
3413
  return record(await deps.engine.activate(owner, {
2809
3414
  situation: args.situation,
2810
- characters: args.characters
3415
+ characters: args.characters,
3416
+ ...args.wakes === void 0 ? {} : { wakes: args.wakes }
2811
3417
  }, run, exec.signal));
2812
3418
  }
2813
3419
  });
@@ -2838,6 +3444,14 @@ function createTools$1(deps) {
2838
3444
  required: true,
2839
3445
  description: "What concretely happens to the character, in a sentence. It becomes what the character is doing."
2840
3446
  },
3447
+ off_routine_minutes: {
3448
+ type: "integer",
3449
+ description: "For a character that has a daily routine: how long, in minutes, from now until it is free to go back to its routine, counting the whole time away and not only the way there (an errand, a vigil, a long talk). Never for the player's character, who has no routine. Always give it when the character is told or chooses to stay, wait, watch or keep going until something happens or someone returns (\"wait however long it takes\"): then count generously, past the longest the wait could last, such as 600 for a whole night. Leave it out only for a short detour: it then keeps to what it does until its day next changes, and its routine takes it back after that. A character who is led or sent elsewhere, or woken, is taken off its routine either way."
3450
+ },
3451
+ waits_for_player: {
3452
+ type: "boolean",
3453
+ description: "True when the character is told or chooses to stay, wait or watch until the player's character is with it again, or goes on an errand that ends only when it is back with the player. It then keeps to that until the player comes to it, whatever its routine says, for at most a day. Never for the player's character."
3454
+ },
2841
3455
  roll: {
2842
3456
  type: "integer",
2843
3457
  description: "The id of the dice roll that decided this outcome (the id roll_check gave), when you rolled for it: the result you give must be the roll's."
@@ -2994,6 +3608,8 @@ function createTools$1(deps) {
2994
3608
  ...outcome.public_state === void 0 ? {} : { publicState: outcome.public_state },
2995
3609
  ...outcome.spoken === void 0 ? {} : { spoken: outcome.spoken },
2996
3610
  ...outcome.roll === void 0 ? {} : { roll: outcome.roll },
3611
+ ...outcome.waits_for_player === true ? { waitsForPlayer: true } : {},
3612
+ ...outcome.off_routine_minutes === void 0 ? {} : { offRoutineMinutes: outcome.off_routine_minutes },
2997
3613
  ...outcome.item_changes === void 0 || outcome.item_changes.length === 0 ? {} : { itemChanges: outcome.item_changes.map((change) => ({
2998
3614
  item: change.item,
2999
3615
  action: change.action,
@@ -3416,6 +4032,10 @@ function createTools$1(deps) {
3416
4032
  required: true,
3417
4033
  description: "Whether what the character tries can work: false when any listed rule is broken or it is not viable."
3418
4034
  },
4035
+ goes_to: {
4036
+ type: "string",
4037
+ description: "The key of the place the player's character is going to, only when what it tries is to go, walk or travel to another place, or to enter one (the market, the cellar, home). Leave it out for anything else. If you do not then record the move with resolve_round, you are asked to before the output is delivered."
4038
+ },
3419
4039
  uncertain: {
3420
4040
  type: "boolean",
3421
4041
  required: true,
@@ -3431,14 +4051,19 @@ function createTools$1(deps) {
3431
4051
  schema: { type: "json" },
3432
4052
  render: (_args, value) => [{
3433
4053
  type: "text",
3434
- text: value.allowed ? `Judged: it can work${value.roll === true ? " but it is uncertain: roll for it now with roll_check (list_checks shows the checks), naming the character it is for; nobody is asked to act before the dice are rolled. Then" : ". 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.`
4054
+ text: value.allowed ? `Judged: it can work${value.roll === true ? ` but it is uncertain: roll for it now with roll_check (list_checks shows the checks), naming the character it is for; nobody is asked to act before the dice are rolled.${value.quick === true ? " When nobody else needs to react and nothing moves or changes hands, settle it in one step with roll_and_narrate instead: it rolls for you and ends the turn. Otherwise" : " Then"}` : ". 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.`
3435
4055
  }]
3436
4056
  },
3437
4057
  isConcurrencySafe: () => false,
3438
4058
  async execute(args, exec) {
3439
4059
  const { owner } = ownerOf(exec.agent);
3440
4060
  await deps.engine.checkRules(owner, args.allowed);
3441
- return record(deps.engine.judge(owner, args.allowed, args.reason, args.at, args.uncertain));
4061
+ const judged = deps.engine.judge(owner, args.allowed, args.reason, args.at, args.uncertain, args.goes_to);
4062
+ const store = deps.stores(owner.chat);
4063
+ return record(judged.roll === true && store !== void 0 && toolEnabled(store.settings().tools, "gameMaster", "roll_and_narrate") ? {
4064
+ ...judged,
4065
+ quick: true
4066
+ } : judged);
3442
4067
  }
3443
4068
  }),
3444
4069
  preview,
@@ -3487,7 +4112,317 @@ function externalGiven(registry, board, agent) {
3487
4112
  function externalWithheld(registry, board, agent) {
3488
4113
  return externalTools(registry).map((tool) => tool.name).filter((name) => !externalEnabled(board, agent, name));
3489
4114
  }
4115
+ /** What a character may use besides its own look-ups: nothing while it is away, because nobody is playing to see what it does with a tool. */
4116
+ function charactersGiven(registry, board, away) {
4117
+ return away ? [] : externalGiven(registry, board, "characters");
4118
+ }
4119
+ // src/host/workspace/describe.ts
4120
+ /** What an agent with file tools is told of where they reach: the shared workspace first, then the folders given to this story. Nothing for a story with no workspace. */
4121
+ function foldersLine(roots, language) {
4122
+ const [workspace, ...rest] = roots;
4123
+ if (workspace === void 0) return void 0;
4124
+ const tr = translator(language);
4125
+ const given = rest.map((folder) => folder.write ? tr("{path} (read and write)", { path: folder.path }) : tr("{path} (read only)", { path: folder.path }));
4126
+ return tr("Your file tools reach only these folders, and every path must be a whole path. The shared workspace, which you may read and write: {workspace}.{given}", {
4127
+ workspace: workspace.path,
4128
+ given: given.length === 0 ? "" : tr(" Given for this story: {folders}.", { folders: given.join(tr(", ")) })
4129
+ });
4130
+ }
4131
+ // src/host/orchestration/character-runner.ts
4132
+ /**
4133
+ * Runs each character as a one-shot child of the game master. It is the character and nothing
4134
+ * else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
4135
+ * the memory of that character alone, so characters acting at the same time cannot see each
4136
+ * other's memories.
4137
+ */
4138
+ function characterRunner(deps) {
4139
+ return async (request, signal) => {
4140
+ const brief = deps.boundaries().characterContext.brief(request);
4141
+ const settings = deps.store.settings();
4142
+ const tools = settings.memory.lookup ? createCharacterTools(() => ({
4143
+ session: deps.store.story,
4144
+ turn: request.turn,
4145
+ policy: settings.memory,
4146
+ queryVector: deps.store.queryVector
4147
+ }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)).map((tool) => notingEmpty(tool, deps.store, request.turn, request.member.character.name)) : [];
4148
+ const background = (request.knowledge?.lore.length ?? 0) > 0 && tools.some((tool) => tool.name === "recall_my_lore");
4149
+ const external = charactersGiven(deps.parent.ctx.tools, settings.tools, request.away === true);
4150
+ const folders = external.length === 0 ? void 0 : await deps.store.folders?.().then((roots) => foldersLine(roots, languageOf$1(settings.prompts.language)));
4151
+ const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
4152
+ return parseCharacterAction(await runChild({
4153
+ parent: deps.parent,
4154
+ signal,
4155
+ sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
4156
+ ...childModel(settings, "characters", named),
4157
+ trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named, request.away === true ? "off stage" : void 0),
4158
+ reasoningEffort: deps.store.settings().reasoning.children,
4159
+ persona: brief.persona,
4160
+ prompt: folders === void 0 ? brief.prompt : `${brief.prompt}\n\n${folders}`,
4161
+ tools,
4162
+ external,
4163
+ maxCalls: deps.store.settings().memory.lookupCalls + (external.length === 0 ? 0 : EXTERNAL_CALLS),
4164
+ result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
4165
+ unenforced: ["thought"],
4166
+ beforeSubmit: submitGate(settings.prompts.language, background, request.away === true ? [] : ownLines(deps.store, request.member.character))
4167
+ }));
4168
+ };
4169
+ }
4170
+ /** A look-up that finds nothing is kept in the turn's trace: it is where the world lacks what a character reached for. */
4171
+ function notingEmpty(tool, store, turn, character) {
4172
+ return {
4173
+ ...tool,
4174
+ async execute(args, exec) {
4175
+ const found = await tool.execute(args, exec);
4176
+ const about = args.about;
4177
+ if (Array.isArray(found) && found.length === 0 && typeof about === "string" && about.trim() !== "") try {
4178
+ store.recordTrace?.(turn, {}, (current) => ({ missing: [...current.missing ?? [], {
4179
+ character,
4180
+ tool: tool.name,
4181
+ about: about.trim().slice(0, 120)
4182
+ }].slice(-40) }));
4183
+ } catch {}
4184
+ return found;
4185
+ }
4186
+ };
4187
+ }
4188
+ const BACKGROUND_CHECK = "before you answer: does this moment touch your own past, skills, training, secrets or what you know of a person or place? If it does, read that background first with recall_my_lore (about: the subject) and answer from it; if it does not, submit the same answer again unchanged";
4189
+ /** The model decides whether the moment touches its background; asking once at the point of answering is what makes it decide. */
4190
+ function submitGate(language, background, said = []) {
4191
+ let asked = !background;
4192
+ let reminded = false;
4193
+ const tr = translator(languageOf$1(language));
4194
+ return (value) => {
4195
+ if (!asked) {
4196
+ asked = true;
4197
+ return BACKGROUND_CHECK;
4198
+ }
4199
+ const wrong = spokenIn(language, value);
4200
+ if (wrong !== void 0) return wrong;
4201
+ const line = value.utterance;
4202
+ if (!reminded && line !== void 0 && said.some((earlier) => sameWords(earlier, line))) {
4203
+ reminded = true;
4204
+ return tr("you already said exactly this earlier in the story: \"{line}\". Say something new that answers this moment, or give no utterance", { line });
4205
+ }
4206
+ };
4207
+ }
4208
+ /** What a character has said in the story so far, most recent last, as the records keep it. */
4209
+ function ownLines(store, character) {
4210
+ const opening = `${character.name}: "`;
4211
+ return store.story.events.list({ involving: character.id }).flatMap((event) => event.text.startsWith(opening) && event.text.endsWith("\"") ? [event.text.slice(opening.length, -1)] : []).slice(-12);
4212
+ }
4213
+ /** What a character that was given tools of other plugins may call on top of its memory look-ups. */
4214
+ const EXTERNAL_CALLS = 5;
4215
+ /** 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. */
4216
+ function spokenIn(language, value) {
4217
+ const given = value;
4218
+ return wrongLanguage(language, {
4219
+ thought: given.thought,
4220
+ intent: given.intent,
4221
+ utterance: given.utterance,
4222
+ account: given.account
4223
+ }, { strays: true }) ?? narratedSpeech(given.utterance);
4224
+ }
4225
+ const CLOSING_QUOTE = {
4226
+ "\"": "\"",
4227
+ "“": "”",
4228
+ "「": "」",
4229
+ "『": "』"
4230
+ };
4231
+ function outsideQuotedSpeech(utterance) {
4232
+ const parts = [];
4233
+ let outside = 0;
4234
+ let cursor = 0;
4235
+ while (cursor < utterance.length) {
4236
+ const closing = CLOSING_QUOTE[utterance[cursor]];
4237
+ if (closing === void 0) {
4238
+ cursor += 1;
4239
+ continue;
4240
+ }
4241
+ const end = utterance.indexOf(closing, cursor + 1);
4242
+ if (end < 0) {
4243
+ cursor += 1;
4244
+ continue;
4245
+ }
4246
+ parts.push(utterance.slice(outside, cursor));
4247
+ outside = end + 1;
4248
+ cursor = outside;
4249
+ }
4250
+ parts.push(utterance.slice(outside));
4251
+ return parts;
4252
+ }
4253
+ /** Writing instructions that ask for prose from the character's own point of view lead it to put its actions between its lines; the utterance is only what is said aloud. */
4254
+ function narratedSpeech(utterance) {
4255
+ if (utterance === void 0) return void 0;
4256
+ const parts = outsideQuotedSpeech(utterance);
4257
+ if (parts.length - 1 < 2) return void 0;
4258
+ return parts.slice(1, -1).some((part) => part.replace(/[\s\p{P}]/gu, "").length >= 6) ? "the utterance holds more than the words said aloud: put what you do in intent and write in the utterance only what you say, with nothing between your lines" : void 0;
4259
+ }
4260
+ /** What the character was reminded of and why, for the run's record, when the recall said why. */
4261
+ function recalledOf(request) {
4262
+ const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
4263
+ return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
4264
+ clarity,
4265
+ turn,
4266
+ text,
4267
+ why
4268
+ })) };
4269
+ }
4270
+ const ANSWER_SCHEMA = {
4271
+ type: "object",
4272
+ properties: { answer: {
4273
+ type: "string",
4274
+ description: "The answer to the player, in plain words, in a few sentences."
4275
+ } },
4276
+ required: ["answer"],
4277
+ additionalProperties: false
4278
+ };
4279
+ /**
4280
+ * 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
4281
+ * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
4282
+ */
4283
+ function answerRunner(deps) {
4284
+ return async (request, signal) => {
4285
+ const brief = deps.boundaries().characterContext.brief(request);
4286
+ return (await runChild({
4287
+ parent: deps.parent,
4288
+ signal,
4289
+ sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
4290
+ ...childModel(deps.store.settings(), "records"),
4291
+ trace: childTrace(deps.store, "records", "answer to the player"),
4292
+ reasoningEffort: deps.store.settings().reasoning.children,
4293
+ persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
4294
+ prompt: brief.prompt,
4295
+ tools: [],
4296
+ maxCalls: 3,
4297
+ result: ANSWER_SCHEMA
4298
+ })).answer;
4299
+ };
4300
+ }
4301
+ // src/shared/dream.ts
4302
+ /** The dream a player asks to enter (`/dream`, `/dream Clara`, `/dream 做梦的人`), or nothing when the message does not start with `/dream`. `who` is empty when no one is named. */
4303
+ function parseDream(text) {
4304
+ const value = text.trimStart();
4305
+ if (value.slice(0, 6).toLowerCase() !== "/dream" || value.length > 6 && !/\s/u.test(value[6])) return void 0;
4306
+ return { who: value.slice(6).trim() };
4307
+ }
4308
+ // src/shared/roll.ts
4309
+ /** The roll in a player's message, or nothing when the message does not start with `/roll`. The notation may be empty, and is then refused. */
4310
+ function parseRoll(text) {
4311
+ const value = text.trimStart();
4312
+ if (value.slice(0, 5).toLowerCase() !== "/roll" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
4313
+ const body = value.slice(5).trimStart();
4314
+ const boundary = body.search(/\s/u);
4315
+ return boundary < 0 ? {
4316
+ expression: body,
4317
+ reason: ""
4318
+ } : {
4319
+ expression: body.slice(0, boundary),
4320
+ reason: body.slice(boundary).trim()
4321
+ };
4322
+ }
4323
+ // src/shared/wait.ts
4324
+ const UNITS = [
4325
+ [/^(?:m|min|mins|minute|minutes|分钟|分)$/iu, 1],
4326
+ [/^(?:h|hr|hrs|hour|hours|小时|時間|时)$/iu, 60],
4327
+ [/^(?:d|day|days|天|日)$/iu, 1440]
4328
+ ];
4329
+ /**
4330
+ * The wait in a player's message (`/wait 2 hours`, `/wait 30m until the ferry`, `/wait 3天`), or nothing when the message does not start with `/wait`. The time may be missing or
4331
+ * unreadable, and is then `undefined` in `minutes`.
4332
+ */
4333
+ function parseWait(text) {
4334
+ const value = text.trimStart();
4335
+ if (value.slice(0, 5).toLowerCase() !== "/wait" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
4336
+ const body = value.slice(5).trim();
4337
+ const match = /^(\d+(?:\.\d+)?)\s*([\p{L}]+)\s*(.*)$/su.exec(body);
4338
+ if (match === null) return {
4339
+ minutes: void 0,
4340
+ reason: body
4341
+ };
4342
+ const unit = UNITS.find(([pattern]) => pattern.test(match[2]));
4343
+ if (unit === void 0) return {
4344
+ minutes: void 0,
4345
+ reason: body
4346
+ };
4347
+ const minutes = Math.round(Number(match[1]) * unit[1]);
4348
+ return {
4349
+ minutes: minutes >= 1 && minutes <= 525600 ? minutes : void 0,
4350
+ reason: match[3].trim()
4351
+ };
4352
+ }
4353
+ // src/host/agents/repeat-guard.ts
4354
+ /**
4355
+ * Keeps an agent that is stuck from making the same call again and again (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one
4356
+ * refused round resolution): past `limit` identical calls in one turn the call is refused with a word that sends it on, and when it goes on regardless the turn is ended. The count starts over at the first step of every turn.
4357
+ * @param languageOf the language of the chat the call belongs to, or nothing when the guard does not apply to it.
4358
+ */
4359
+ function guardRepeatedCalls(ctx, languageOf, limit) {
4360
+ const calls = /* @__PURE__ */ new Map();
4361
+ ctx.on("agent/pre-step", async (payload, next) => {
4362
+ if (payload.step === 1) calls.delete(payload.agent.session.id);
4363
+ return await next();
4364
+ });
4365
+ ctx.on("tools/pre-execute", async (exec, next) => {
4366
+ const chat = exec.agent?.session.id;
4367
+ const language = chat === void 0 || exec.agent?.session.header.origin === "subagent" ? void 0 : languageOf(exec);
4368
+ if (chat === void 0 || language === void 0) return await next();
4369
+ const signature = `${exec.name}:${JSON.stringify(exec.arguments)}`;
4370
+ const seen = calls.get(chat) ?? /* @__PURE__ */ new Map();
4371
+ calls.set(chat, seen);
4372
+ const count = (seen.get(signature) ?? 0) + 1;
4373
+ seen.set(signature, count);
4374
+ if (count <= limit) return await next();
4375
+ if (count > limit + 5) exec.agent?.cancel({ kind: "user" }, { keepInbox: true });
4376
+ return {
4377
+ kind: "deny",
4378
+ reason: translator(languageOf$1(language))("This exact call was already made {count} times in this turn with the same result. Do not repeat it: go on with the next step, or finish and say what is left.", { count: count - 1 })
4379
+ };
4380
+ }, { prepend: true });
4381
+ }
4382
+ // src/host/orchestration/runaway.ts
4383
+ /** The levels of thinking that mean none, as models name them. */
4384
+ const NONE = [
4385
+ "off",
4386
+ "none",
4387
+ "minimal"
4388
+ ];
4389
+ /**
4390
+ * A game master whose thinking ran on to the end of its output limit (found live: 12000 tokens, two and a half minutes, and a turn that ended without output) is asked to answer
4391
+ * without thinking for the rest of the turn, when its model offers that. The level it was on is put back at the first step of the next turn.
4392
+ */
4393
+ var RunawayThinking = class {
4394
+ before = /* @__PURE__ */ new Map();
4395
+ /** To be called before each step of a chat's game master. */
4396
+ async step(chat, agent, step) {
4397
+ const earlier = this.before.get(chat);
4398
+ if (earlier !== void 0 && step === 1) {
4399
+ agent.model.select(earlier);
4400
+ this.before.delete(chat);
4401
+ return;
4402
+ }
4403
+ if (step === 1 || earlier !== void 0 || !cutOff(agent)) return;
4404
+ const current = agent.model.current();
4405
+ if (current === void 0) return;
4406
+ const level = (await agent.ctx.llm.resolveModelInfo(current.provider, current.model, new AbortController().signal).catch(() => void 0))?.reasoning?.efforts.find((effort) => NONE.includes(effort.id));
4407
+ if (level === void 0 || current.reasoningEffort === level.id) return;
4408
+ this.before.set(chat, current);
4409
+ agent.model.select({
4410
+ ...current,
4411
+ reasoningEffort: ReasoningEffortId(level.id)
4412
+ });
4413
+ }
4414
+ };
3490
4415
  // src/host/orchestration/hooks.ts
4416
+ /** DSH's file tools that a story may give its game master. */
4417
+ const FILE_TOOLS = [
4418
+ "read",
4419
+ "read_image",
4420
+ "write",
4421
+ "edit",
4422
+ "glob",
4423
+ "grep",
4424
+ "apply_patch"
4425
+ ];
3491
4426
  const notice = (text) => createUserMessage({
3492
4427
  content: [{
3493
4428
  type: "text",
@@ -3566,6 +4501,43 @@ function installHooks(ctx, deps) {
3566
4501
  }
3567
4502
  }))];
3568
4503
  };
4504
+ const runaway = new RunawayThinking();
4505
+ const turns = deps.traces ?? new TurnTraces(() => tracerOf(ctx));
4506
+ engine.observe = (chat, round) => {
4507
+ const span = turns.child(chat, {
4508
+ name: round.attempt === 1 ? "round" : "round (retry)",
4509
+ kind: "span",
4510
+ input: {
4511
+ characters: round.characters,
4512
+ ...round.away ? { away: true } : {}
4513
+ },
4514
+ metadata: {
4515
+ turn: round.turn,
4516
+ attempt: round.attempt
4517
+ }
4518
+ });
4519
+ return (result) => {
4520
+ if (span === void 0) return;
4521
+ if (result instanceof Error) {
4522
+ span.end({
4523
+ level: "ERROR",
4524
+ statusMessage: result.message
4525
+ });
4526
+ return;
4527
+ }
4528
+ span.end({ output: {
4529
+ acted: result.reports.map((report) => ({
4530
+ character: report.name,
4531
+ intent: report.intent,
4532
+ commitment: report.commitment
4533
+ })),
4534
+ failed: result.failures.map((failure) => ({
4535
+ character: failure.name,
4536
+ reason: failure.reason
4537
+ }))
4538
+ } });
4539
+ };
4540
+ };
3569
4541
  guardRepeatedCalls(ctx, (exec) => {
3570
4542
  const owner = exec.agent === void 0 ? void 0 : ownerOf(exec.agent, 0);
3571
4543
  return owner === void 0 ? void 0 : stores(owner.chat)?.settings().prompts.language;
@@ -3580,6 +4552,7 @@ function installHooks(ctx, deps) {
3580
4552
  ctx.on("session/event", (session, event) => {
3581
4553
  if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
3582
4554
  ctx.roleplayOrchestration.recovery.clear(session.id);
4555
+ turns.end(session.id);
3583
4556
  timelines.ended(session.id, session, event.seq);
3584
4557
  const events = session.snapshotEvents();
3585
4558
  const began = events.findLastIndex((entry) => entry.type === "turn/start");
@@ -3607,7 +4580,7 @@ function installHooks(ctx, deps) {
3607
4580
  if (owner === void 0) return;
3608
4581
  const missing = engine.missing(owner);
3609
4582
  if (missing === void 0) return;
3610
- if (!engine.object(owner, missing)) {
4583
+ if (!engine.object(owner, missing, finishOf(agent) === "tool-calls")) {
3611
4584
  ctx.logger.warn(`roleplay: ${owner.chat} ended turn ${turn} without finishing it (${missing})`);
3612
4585
  return;
3613
4586
  }
@@ -3623,7 +4596,13 @@ function installHooks(ctx, deps) {
3623
4596
  });
3624
4597
  ctx.on("agent/pre-step", async (payload, next) => {
3625
4598
  const decision = await next();
4599
+ const selected = payload.agent.model.current();
4600
+ if (decision.kind === "enter") await ctx.roleplayOrchestration.residency?.ensure("main", selected === void 0 ? void 0 : {
4601
+ provider: selected.provider,
4602
+ model: selected.model
4603
+ });
3626
4604
  const owner = ownerOf(payload.agent, payload.turn);
4605
+ if (decision.kind === "enter" && owner !== void 0) await runaway.step(owner.chat, payload.agent, payload.step);
3627
4606
  const store = owner === void 0 ? void 0 : stores(owner.chat);
3628
4607
  if (owner !== void 0 && store !== void 0) applyLimit(payload.agent, store);
3629
4608
  if (decision.kind !== "enter" || payload.step !== 1) return decision;
@@ -3632,11 +4611,13 @@ function installHooks(ctx, deps) {
3632
4611
  if (!store.settings().background.concurrent) await engine.quiesce(owner.chat, { skipOptional: true });
3633
4612
  await ctx.roleplayOrchestration.unitFree(owner.chat);
3634
4613
  const began = await timelines.begin(owner.chat, payload.turn, text);
4614
+ turns.begin(owner.chat, payload.turn, text);
3635
4615
  deps.rolls?.begin(owner.chat, store.story.metadata.get().id, began.parent);
3636
4616
  const cast = store.cast();
3637
4617
  const ooc = parseOoc(text);
3638
4618
  const command = ooc === void 0 ? /^\/([\p{L}\p{N}_]+)/u.exec(text.trim())?.[1] : void 0;
3639
4619
  const used = store.raiseCommand?.(command, payload.turn);
4620
+ const dream = ooc === void 0 ? parseDream(text) : void 0;
3640
4621
  const verdict = ooc === void 0 ? boundaries().inputValidator.validate({
3641
4622
  text,
3642
4623
  turn: payload.turn,
@@ -3644,7 +4625,7 @@ function installHooks(ctx, deps) {
3644
4625
  }) : { ok: true };
3645
4626
  if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
3646
4627
  else if (ooc === void 0) {
3647
- engine.expectJudgement(owner);
4628
+ if (dream === void 0) engine.expectJudgement(owner);
3648
4629
  engine.noteInput(owner, text);
3649
4630
  }
3650
4631
  const queryVector = await store.queryVector(ooc?.request ?? text);
@@ -3656,6 +4637,7 @@ function installHooks(ctx, deps) {
3656
4637
  name: move.name,
3657
4638
  place: move.to
3658
4639
  })));
4640
+ const arrived = store.autonomy?.inbox() ?? [];
3659
4641
  const world = {
3660
4642
  happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
3661
4643
  names: cue.names.join(tr(" and ")),
@@ -3711,9 +4693,13 @@ function installHooks(ctx, deps) {
3711
4693
  }), ...commandBringsPeopleIn(store, used) ? [tr("The world itself brings in anyone this command calls for, after this turn: do not make them up yourself with expand_world.")] : []].join(" "));
3712
4694
  if (pacing !== void 0) addLine("pacing", describePacingAdvice(pacing));
3713
4695
  else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) addLine("pacing", store.text("roleplay/plot-hint"));
4696
+ const filing = FILE_TOOLS.some((name) => externalEnabled(store.settings().tools, "gameMaster", name)) ? await deps.folders?.(owner.chat) : void 0;
4697
+ const folderLine = filing === void 0 ? void 0 : foldersLine(filing, languageOf$1(store.settings().prompts.language) === "zh" ? "zh" : "en");
4698
+ if (folderLine !== void 0) addLine("folders", folderLine);
4699
+ if (arrived.length > 0) addLine("messages", tr("While the player was away, these messages reached their character, who has read them: {messages}. Refer to them only if the player does.", { messages: arrived.map((message) => `${message.name}: "${message.text}"`).join(" ") }));
3714
4700
  const rules = store.rules();
3715
4701
  if (rules.length > 0) addLine("rules", store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
3716
- const wanted = ooc === void 0 ? parseRoll(text) : void 0;
4702
+ const wanted = ooc === void 0 && dream === void 0 ? parseRoll(text) : void 0;
3717
4703
  if (wanted !== void 0) try {
3718
4704
  const made = rollPlain(wanted.expression, deps.rolls?.roller(owner.chat));
3719
4705
  const roll = store.story.dice.record({
@@ -3737,18 +4723,81 @@ function installHooks(ctx, deps) {
3737
4723
  engine.skip(owner);
3738
4724
  lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
3739
4725
  }
3740
- const waiting = ooc === void 0 && wanted === void 0 ? parseWait(text) : void 0;
4726
+ if (dream !== void 0) {
4727
+ const sleepers = store.sleepers(payload.turn);
4728
+ const wantedName = dream.who.toLowerCase();
4729
+ const found = wantedName === "" ? sleepers.length === 1 ? sleepers : [] : sleepers.filter((entry) => entry.key.toLowerCase() === wantedName || [entry.name, ...entry.aliases ?? []].some((name) => name.toLowerCase().includes(wantedName)));
4730
+ const refusal = !store.settings().schedule.enabled ? tr("this chat keeps no days for its characters, so nobody sleeps and there is no dream to enter") : sleepers.length === 0 ? tr("nobody is asleep, so there is no dream to enter") : found.length === 0 ? tr("say whose dream: {names}", { names: sleepers.map((entry) => entry.name).join(tr(", ")) }) : found.length > 1 ? tr("more than one is asleep ({names}): say whose dream", { names: found.map((entry) => entry.name).join(tr(", ")) }) : void 0;
4731
+ if (refusal !== void 0) {
4732
+ engine.skip(owner);
4733
+ lines.push(store.text("roleplay/input-refused", { reason: refusal }));
4734
+ } else {
4735
+ const sleeper = found[0];
4736
+ engine.beginDream(owner, sleeper.key, tr("You are asleep and the player's character has come into your dream. Say what the dream holds."));
4737
+ const report = await engine.dream(owner, characterRunner({
4738
+ parent: payload.agent,
4739
+ boundaries,
4740
+ store
4741
+ }));
4742
+ const asked = report === void 0 ? tr("Ask {name} (activate_characters with only {key}; the sleeper stays asleep and needs no wakes) what the dream holds, then narrate it.", {
4743
+ name: sleeper.name,
4744
+ key: sleeper.key
4745
+ }) : tr("{name} has already been asked and answered from the dream: intent \"{intent}\"{said}. Ask nobody and call no tool but narrate, with narration segments only, and put what {name} says in the narration.", {
4746
+ name: sleeper.name,
4747
+ intent: report.intent,
4748
+ said: report.utterance === void 0 || report.utterance === "" ? "" : tr(", said \"{text}\"", { text: report.utterance })
4749
+ });
4750
+ addLine("dream", store.text("roleplay/dream", {
4751
+ name: sleeper.name,
4752
+ key: sleeper.key,
4753
+ asked
4754
+ }));
4755
+ }
4756
+ }
4757
+ const waiting = ooc === void 0 && wanted === void 0 && dream === void 0 ? parseWait(text) : void 0;
3741
4758
  if (waiting !== void 0) {
3742
4759
  const clock = store.settings().clock;
3743
4760
  const refusal = clock.mode === "real" ? tr("this chat follows the clock on the wall, so time cannot be skipped") : waiting.minutes === void 0 ? tr("say how long, for example /wait 2 hours or /wait 30 minutes until the ferry") : waiting.minutes > clock.maxSkipDays * 1440 ? tr("that is more than the {days} days this chat allows in one skip", { days: clock.maxSkipDays }) : void 0;
3744
4761
  if (refusal !== void 0) {
3745
4762
  engine.skip(owner);
3746
4763
  lines.push(store.text("roleplay/input-refused", { reason: refusal }));
3747
- } else addLine("wait", tr("The player lets {minutes} minutes pass{reason}. Move the story's time on by that much with advance_time, and let the world move meanwhile as it would: characters keep to their days, and you ask only those the time reaches. Stop sooner, at the moment it happens, if something comes up that the player must decide or could not sleep through, say what, and let the player act. Then narrate what the player perceived in the time that passed. You may play at most {rounds} rounds for this.", {
3748
- minutes: waiting.minutes,
3749
- reason: waiting.reason === "" ? "" : ` (${waiting.reason})`,
3750
- rounds: store.settings().maxRounds
3751
- }));
4764
+ } else {
4765
+ const reason = waiting.reason === "" ? "" : ` (${waiting.reason})`;
4766
+ const language = languageOf$1(store.settings().prompts.language) === "zh" ? "zh" : "en";
4767
+ const skipped = (() => {
4768
+ try {
4769
+ return engine.advanceTime(owner, {
4770
+ byMinutes: waiting.minutes,
4771
+ reason: waiting.reason === "" ? tr("time passes") : waiting.reason
4772
+ });
4773
+ } catch {
4774
+ return;
4775
+ }
4776
+ })();
4777
+ if (skipped === void 0) addLine("wait", tr("The player lets {minutes} minutes pass{reason}. Move the story's time on by that much with advance_time, and let the world move meanwhile as it would: characters keep to their days, and you ask only those the time reaches. Stop sooner, at the moment it happens, if something comes up that the player must decide or could not sleep through, say what, and let the player act. Then narrate what the player perceived in the time that passed. You may play at most {rounds} rounds for this.", {
4778
+ minutes: waiting.minutes,
4779
+ reason,
4780
+ rounds: store.settings().maxRounds
4781
+ }));
4782
+ else {
4783
+ const moved = skipped.moved.map((move) => tr("{name} went to {place}.", {
4784
+ name: move.name,
4785
+ place: move.to
4786
+ })).join(" ");
4787
+ const happened = skipped.world.flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
4788
+ names: cue.names.join(tr(" and ")),
4789
+ text: cue.text
4790
+ }))]).join(" ");
4791
+ addLine("wait", tr("The player let {minutes} minutes pass{reason}, and the story's time has already been moved on to {now}: do not call advance_time for it. {moved}{happened}Narrate what the player perceived in that time, in the story's own terms. If something in it would have made the player act or woken them, let it come at the end and stop there. You may play at most {rounds} rounds for this.", {
4792
+ minutes: waiting.minutes,
4793
+ reason,
4794
+ now: describeInstant(skipped.to, skipped.zone, language),
4795
+ moved: moved === "" ? "" : `${moved} `,
4796
+ happened: happened === "" ? "" : `${happened} `,
4797
+ rounds: store.settings().maxRounds
4798
+ }));
4799
+ }
4800
+ }
3752
4801
  }
3753
4802
  if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
3754
4803
  if (ooc !== void 0 && ooc.request === "") {
@@ -3769,6 +4818,6 @@ function installHooks(ctx, deps) {
3769
4818
  };
3770
4819
  });
3771
4820
  }
3772
- export { listFiles as $, LANGUAGE_NAMES as A, COMMANDS_KEY as B, readNotes as C, PLOTS_METADATA_KEY as D, answerLimits as E, readUsage as F, formatIssue as G, commandsOf as H, PLOTS_FILE_NAME as I, PROMPTS_FOLDER as J, errorMessage as K, loadPlots as L, isStoryLanguage as M, textLanguage as N, plotProgressOf as O, wrongLanguage as P, languageOf as Q, parsePlotsFile as R, notesOfSession as S, RESULTS as T, readDocument as U, commandFlagKey as V, Reader as W, copyWorldPrompts as X, PromptLibrary as Y, inheritPrompts as Z, readTraces as _, externalWithheld as a, InvalidStartError as at, readWithdrawn as b, record as c, SessionArchivedError as ct, guardRepeatedCalls as d, ClockError as dt, promptProblem as et, MAX_OOC_ANSWER as f, describeTime as ft, readRunDetail as g, COMPARISONS as gt, readActivity as h, AUTHORING_NEEDS as ht, externalTools as i, AgentUnavailableError as it, STORY_LANGUAGES as j, populatePlots as k, characterRunner as l, SessionNotFoundError as lt, readDecisionStats as m, zoneOf as mt, installHooks as n, shippedPromptsDirectory as nt, PREVIEW_TOOL as o, InvalidWorldError as ot, storesOf as p, describeWhen as pt, LANGUAGE_FOLDER as q, externalGiven as r, shippedText as rt, createTools$1 as s, ReflectionRefusedError as st, externalToolLimit as t, shippedLanguages as tt, toolEnabled as u, WorldNotFoundError as ut, readVerdicts as v, observeAsPlayer as w, addToNote as x, writeVerdicts as y, plotReferenceProblems as z };
4821
+ export { inheritPrompts as $, plotProgressOf as A, parsePlotsFile as B, readNotes as C, referent as D, sameWords as E, textLanguage as F, readDocument as G, COMMANDS_KEY as H, wrongLanguage as I, errorMessage as J, Reader as K, readUsage as L, LANGUAGE_NAMES as M, STORY_LANGUAGES as N, RESULTS as O, isStoryLanguage as P, copyWorldPrompts as Q, PLOTS_FILE_NAME as R, notesOfSession as S, defaultBoundaries as T, commandFlagKey as U, plotReferenceProblems as V, commandsOf as W, PROMPTS_FOLDER as X, LANGUAGE_FOLDER as Y, PromptLibrary as Z, readTraces as _, COMPARISONS as _t, externalGiven as a, shippedText as at, readWithdrawn as b, PREVIEW_TOOL as c, InvalidWorldError as ct, toolEnabled as d, SessionNotFoundError as dt, languageOf as et, MAX_OOC_ANSWER as f, WorldNotFoundError as ft, readRunDetail as g, AUTHORING_NEEDS as gt, readActivity as h, zoneOf as ht, characterRunner as i, shippedPromptsDirectory as it, populatePlots as j, PLOTS_METADATA_KEY as k, createTools$1 as l, ReflectionRefusedError as lt, readDecisionStats as m, describeWhen as mt, installHooks as n, promptProblem as nt, externalTools as o, AgentUnavailableError as ot, storesOf as p, ClockError as pt, formatIssue as q, guardRepeatedCalls as r, shippedLanguages as rt, externalWithheld as s, InvalidStartError as st, externalToolLimit as t, listFiles as tt, record as u, SessionArchivedError as ut, readVerdicts as v, observeAsPlayer as w, addToNote as x, writeVerdicts as y, loadPlots as z };
3773
4822
 
3774
- //# sourceMappingURL=hooks-DORky4KT.js.map
4823
+ //# sourceMappingURL=hooks-BNeoGMHZ.js.map