@dsh-agentic-roleplay/core 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/lib/authoring.js +18 -223
  2. package/lib/client.js +903 -478
  3. package/lib/client.js.map +1 -1
  4. package/lib/compaction.js +1 -1
  5. package/lib/{deliver--uMhC6oO.js → deliver-BDW5WZvc.js} +579 -195
  6. package/lib/{documents-7GMc5NnW.js → documents-DtlY2IRt.js} +857 -12
  7. package/lib/{gallery-DUeBMHQX.js → gallery-DACG5eh2.js} +2 -2
  8. package/lib/{generator-HPifO3Kk.js → generator-DGYcLMp7.js} +2 -2
  9. package/lib/images.js +3 -3
  10. package/lib/index.js +181 -11
  11. package/lib/{narration-CKZTk5UE.js → narration-5ig7Dg28.js} +3 -2
  12. package/lib/orchestration.js +366 -274
  13. package/lib/{packs-alJTiDM2.js → packs-CkRZDCsV.js} +49 -5
  14. package/lib/{presenter-agent-PX1WVaJB.js → presenter-agent-PK9JYExk.js} +3 -3
  15. package/package.json +4 -4
  16. package/packs/scene/strip.js +1 -1
  17. package/prompts/en/roleplay/character-decide.md +1 -1
  18. package/prompts/en/roleplay/character-rules.md +1 -1
  19. package/prompts/en/roleplay/chronicler.md +1 -1
  20. package/prompts/en/roleplay/game-master.md +1 -1
  21. package/prompts/en/roleplay/reflection.md +2 -2
  22. package/prompts/en/roleplay/style.md +1 -1
  23. package/prompts/en/roleplay/suggester.md +1 -1
  24. package/prompts/en/translate/document.md +6 -0
  25. package/prompts/en/translate/glossary.md +5 -0
  26. package/prompts/en/translate/notice.md +2 -0
  27. package/prompts/zh/roleplay/character-decide.md +1 -1
  28. package/prompts/zh/roleplay/character-rules.md +1 -1
  29. package/prompts/zh/roleplay/chronicler.md +1 -1
  30. package/prompts/zh/roleplay/game-master.md +1 -1
  31. package/prompts/zh/roleplay/reflection.md +2 -2
  32. package/prompts/zh/roleplay/style.md +1 -1
  33. package/prompts/zh/roleplay/suggester.md +1 -1
  34. package/prompts/zh/translate/document.md +6 -0
  35. package/prompts/zh/translate/glossary.md +5 -0
  36. package/prompts/zh/translate/notice.md +2 -0
@@ -1,11 +1,11 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { F as shippedText, W as INTENT_STATUSES, _ as API_PREFIX, b as parsePlotsFile, z as ReflectionRefusedError } from "./packs-alJTiDM2.js";
3
- import { B as skipTime, D as observeSurroundings, E as observeAsPlayer, F as beginTurn, G as RESULTS, H as referent, I as describeTime, K as answerEstimate, L as describeWhen, N as sameWords, P as ClockError, R as endRound, S as clearNotes, T as readNotes, U as AWAY_ACTION_SCHEMA, V as zoneOf, W as CHARACTER_ACTION_SCHEMA, _ as plotAuthorNeeded, b as updatePlotProgress, c as dueReflection, f as whereabouts, g as pacingAdvice, h as describePacingAdvice, i as keepRunDetail, k as Timelines, l as memoryReflector, m as addSessionPlot, q as parseCharacterAction, r as forgetRunDetails, s as recordActivity, t as deliverNow, u as recordFailure, w as putNote, x as addToNote, z as readTime } from "./deliver--uMhC6oO.js";
4
- import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-CKZTk5UE.js";
2
+ import { B as shippedText, S as wrongLanguage, T as parsePlotsFile, W as ReflectionRefusedError, Y as INTENT_STATUSES, _ as API_PREFIX } from "./packs-CkRZDCsV.js";
3
+ import { B as skipTime, D as observeSurroundings, E as observeAsPlayer, F as beginTurn, G as RESULTS, H as referent, I as describeTime, J as languageOf, K as answerEstimate, L as describeWhen, N as sameWords, P as ClockError, R as endRound, S as clearNotes, T as readNotes, U as AWAY_ACTION_SCHEMA, V as zoneOf, W as CHARACTER_ACTION_SCHEMA, Y as translator, _ as plotAuthorNeeded, b as updatePlotProgress, c as dueReflection, f as whereabouts, g as pacingAdvice, h as describePacingAdvice, i as keepRunDetail, k as Timelines, l as memoryReflector, m as addSessionPlot, q as parseCharacterAction, r as forgetRunDetails, s as recordActivity, t as deliverNow, u as recordFailure, w as putNote, x as addToNote, z as readTime } from "./deliver-BDW5WZvc.js";
4
+ import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-5ig7Dg28.js";
5
5
  import "./src-CWTNeL6Y.js";
6
- import { A as runChild, D as childSampling, E as childModel, T as uniqueKey, j as estimateAnswer, k as childTrace, o as addToLibrary, w as slug } from "./generator-HPifO3Kk.js";
7
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DUeBMHQX.js";
8
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PX1WVaJB.js";
6
+ import { A as runChild, D as childSampling, E as childModel, M as tokensOf, T as uniqueKey, j as estimateAnswer, k as childTrace, o as addToLibrary, w as slug } from "./generator-DGYcLMp7.js";
7
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DACG5eh2.js";
8
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PK9JYExk.js";
9
9
  import { join } from "node:path";
10
10
  import { existsSync } from "node:fs";
11
11
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -136,6 +136,16 @@ function keeperTools(job, memory, progress) {
136
136
  execute: async (args, exec) => {
137
137
  const outside = (parseRecordsEdit(args).events ?? []).filter((event) => !job.rounds.some((round) => round.turn === event.turn && round.round === event.round));
138
138
  if (outside.length > 0) throw new InvalidEditError(outside.map((event) => `an event has turn ${event.turn}, round ${event.round}, which is not one of the rounds given: ${job.rounds.map(label).join("; ")}`));
139
+ const edit = parseRecordsEdit(args);
140
+ const wording = wrongLanguage(job.store.settings().prompts.language, {
141
+ events: [...(edit.events ?? []).map((event) => event.text), ...(edit.eventEdits ?? []).map((event) => event.text)].join(" "),
142
+ perceptions: [
143
+ ...(edit.events ?? []).flatMap((event) => (event.perceivedBy ?? []).map((seen) => seen.content)),
144
+ ...(edit.perceptionEdits ?? []).map((seen) => seen.content),
145
+ ...(edit.perceptionsAdded ?? []).map((seen) => seen.content)
146
+ ].join(" ")
147
+ });
148
+ if (wording !== void 0) throw new InvalidEditError([wording]);
139
149
  const result = await tool.execute(args, exec);
140
150
  progress.edits += 1;
141
151
  progress.unchecked = true;
@@ -160,6 +170,9 @@ function keeperTools(job, memory, progress) {
160
170
  return tool;
161
171
  });
162
172
  }
173
+ /** What one request of the keeper may carry: the events and what each witness took in, for every round it was given, and the shape of the call. */
174
+ const KEEPER_CHARACTERS_PER_ROUND = 4e3;
175
+ const keeperEstimate = (rounds, language) => tokensOf(rounds * KEEPER_CHARACTERS_PER_ROUND, language) + 192;
163
176
  /**
164
177
  * Writes rounds into the story's records with a child agent of the game master that has the
165
178
  * record tools to itself (the game master and the characters never see them). It writes with
@@ -186,7 +199,7 @@ function recordKeeper(deps) {
186
199
  parent,
187
200
  signal,
188
201
  reasoningEffort: job.store.settings().reasoning.children,
189
- sampling: childSampling(job.store.settings(), "records"),
202
+ sampling: childSampling(job.store.settings(), "records", keeperEstimate(job.rounds.length, job.store.settings().prompts.language)),
190
203
  ...childModel(job.store.settings(), "records"),
191
204
  trace: childTrace(job.store, "records", "record keeper"),
192
205
  persona: promptFor(parent, "roleplay/record-keeper", job.store.settings().prompts.language),
@@ -358,7 +371,7 @@ function triggerJudge(deps) {
358
371
  parent,
359
372
  signal,
360
373
  reasoningEffort: store.settings().reasoning.children,
361
- sampling: childSampling(store.settings(), "records"),
374
+ sampling: childSampling(store.settings(), "records", statements.length * 2 * 8 + 8),
362
375
  ...childModel(store.settings(), "records"),
363
376
  trace: childTrace(store, "records", "trigger judge"),
364
377
  persona: promptFor(parent, "roleplay/trigger-judge", store.settings().prompts.language),
@@ -391,6 +404,16 @@ const DAY_MS = 864e5;
391
404
  const STRATEGY_ROUND = 200;
392
405
  const MAX_ACTIVE_GOALS = 8;
393
406
  const MAX_TEXT = 400;
407
+ /** What a decision may hold: the summary, both states, a new goal with its plan, and the status of each active goal. */
408
+ const DECISION_LIMITS = [
409
+ MAX_TEXT,
410
+ MAX_TEXT,
411
+ MAX_TEXT,
412
+ 120,
413
+ MAX_TEXT,
414
+ ...Array.from({ length: 6 }, () => 200),
415
+ ...Array.from({ length: MAX_ACTIVE_GOALS }, () => 10)
416
+ ];
394
417
  const keyOf$1 = (faction) => faction.sourceId ?? String(faction.id);
395
418
  function lastActed(session) {
396
419
  const stored = session.metadata.getValue(LAST_KEY);
@@ -563,7 +586,7 @@ function factionStrategist(deps) {
563
586
  parent,
564
587
  signal,
565
588
  reasoningEffort: store.settings().reasoning.children,
566
- sampling: childSampling(store.settings(), "authoring"),
589
+ sampling: childSampling(store.settings(), "authoring", estimateAnswer(DECISION_LIMITS, store.settings().prompts.language)),
567
590
  ...childModel(store.settings(), "authoring"),
568
591
  trace: childTrace(store, "authoring", `faction ${faction.name}`),
569
592
  persona: promptFor(parent, "roleplay/faction-strategist", store.settings().prompts.language),
@@ -582,6 +605,13 @@ function factionStrategist(deps) {
582
605
  }
583
606
  //#endregion
584
607
  //#region src/host/authoring/author-agent.ts
608
+ /** A made-up thing in one edit: its name, description and the handful of fields a character, place or item carries. */
609
+ const THING_TEXTS = 14;
610
+ const THING_TEXT_CHARS = 300;
611
+ /** What consolidating one waiting item writes: a way or a relationship with its descriptions. */
612
+ const FIT_TEXTS = 6;
613
+ const FIT_TEXT_CHARS = 200;
614
+ const editEstimate = (things, texts, chars, language) => estimateAnswer(Array.from({ length: Math.max(1, things) * texts }, () => chars), language);
585
615
  function authorTools(job, work, mode, limits) {
586
616
  const link = {
587
617
  session: job.store.story,
@@ -825,7 +855,7 @@ function worldAuthor(deps) {
825
855
  const work = { created: [] };
826
856
  const result = await runChild({
827
857
  reasoningEffort: job.store.settings().reasoning.children,
828
- sampling: childSampling(job.store.settings(), "authoring"),
858
+ sampling: childSampling(job.store.settings(), "authoring", editEstimate(authoring.perTurn, THING_TEXTS, THING_TEXT_CHARS, job.store.settings().prompts.language)),
829
859
  ...childModel(job.store.settings(), "authoring"),
830
860
  trace: childTrace(job.store, "authoring", "world author"),
831
861
  parent,
@@ -868,7 +898,7 @@ function worldAuthor(deps) {
868
898
  const work = { created: [] };
869
899
  const result = await runChild({
870
900
  reasoningEffort: job.store.settings().reasoning.children,
871
- sampling: childSampling(job.store.settings(), "authoring"),
901
+ sampling: childSampling(job.store.settings(), "authoring", editEstimate(pending.length, FIT_TEXTS, FIT_TEXT_CHARS, job.store.settings().prompts.language)),
872
902
  ...childModel(job.store.settings(), "authoring"),
873
903
  trace: childTrace(job.store, "authoring", "world consolidation"),
874
904
  parent,
@@ -1205,7 +1235,9 @@ function markHandled(session, keys) {
1205
1235
  * whose time has come with everyone to do with them away from the scene, and goals whose deadline has passed.
1206
1236
  * Oldest first.
1207
1237
  */
1208
- function dueOffScene(session, zone, now) {
1238
+ function dueOffScene(session, zone, now, language = "en") {
1239
+ const tr = translator(language);
1240
+ const when = (instant) => describeWhen(instant, now, zone, language);
1209
1241
  const handled = handledKeys(session);
1210
1242
  const characters = session.characters.list();
1211
1243
  const player = characters.find((character) => character.control === "player");
@@ -1228,7 +1260,19 @@ function dueOffScene(session, zone, now) {
1228
1260
  at: engagement.at,
1229
1261
  characters: everyone.map((id) => keyOf(agents.get(id))),
1230
1262
  ...place === void 0 ? {} : { place: place.sourceId ?? String(place.id) },
1231
- text: `You were to ${engagement.title}${place === void 0 ? "" : ` at ${place.name}`}, at ${describeWhen(engagement.at, now, zone)}${engagement.note === "" ? "" : ` (${engagement.note})`}. It is ${describeWhen(now, now, zone)} now${now > engagement.at + ENGAGEMENT_GRACE ? " and the time has passed" : ""}. It was with: ${everyone.map((id) => agents.get(id).name).join(", ")}. You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.`
1263
+ text: [
1264
+ `${place === void 0 ? tr("You were to {title}, at {when}", {
1265
+ title: engagement.title,
1266
+ when: when(engagement.at)
1267
+ }) : tr("You were to {title} at {place}, at {when}", {
1268
+ title: engagement.title,
1269
+ place: place.name,
1270
+ when: when(engagement.at)
1271
+ })}${engagement.note === "" ? "" : tr(" ({note})", { note: engagement.note })}${tr(".")}`,
1272
+ now > engagement.at + ENGAGEMENT_GRACE ? tr("It is {now} now and the time has passed.", { now: when(now) }) : tr("It is {now} now.", { now: when(now) }),
1273
+ tr("It was with: {who}.", { who: everyone.map((id) => agents.get(id).name).join(tr(", ")) }),
1274
+ tr("You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.")
1275
+ ].join(" ")
1232
1276
  });
1233
1277
  }
1234
1278
  for (const character of agents.values()) {
@@ -1247,7 +1291,11 @@ function dueOffScene(session, zone, now) {
1247
1291
  kind: "goal",
1248
1292
  at: deadline,
1249
1293
  characters: [keyOf(character)],
1250
- text: `The time you had for "${goal.name}" has passed (${describeWhen(deadline, now, zone)}; it is ${describeWhen(now, now, zone)} now)${goal.description === "" ? "" : `: ${goal.description}`} You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.`
1294
+ text: `${tr("The time you had for \"{goal}\" has passed ({when}; it is {now} now)", {
1295
+ goal: goal.name,
1296
+ when: when(deadline),
1297
+ now: when(now)
1298
+ })}${goal.description === "" ? "" : `${tr(": ")}${goal.description}`} ${tr("You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.")}`
1251
1299
  });
1252
1300
  }
1253
1301
  }
@@ -1552,7 +1600,7 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
1552
1600
  changeVariables: (turn, changes) => session.transaction(() => changes.map((spec) => changeVariable(session, spec, turn))),
1553
1601
  trackedFor: (characterId, presentIds) => trackedFor(session, characterId, presentIds),
1554
1602
  tracked: () => trackedLines(session),
1555
- dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now),
1603
+ dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now, languageOf(settings().prompts.language)),
1556
1604
  markHandled: (keys) => {
1557
1605
  markHandled(session, keys);
1558
1606
  },
@@ -1730,9 +1778,16 @@ function installHooks(ctx, deps) {
1730
1778
  store.clearNotes();
1731
1779
  store.lapseNotes(payload.turn);
1732
1780
  const { time, away, agenda } = store.beginTurn(payload.turn);
1733
- if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => `${move.name} went to ${move.to}.`));
1781
+ const tr = translator(languageOf(store.settings().prompts.language));
1782
+ if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => tr("{name} went to {place}.", {
1783
+ name: move.name,
1784
+ place: move.to
1785
+ })));
1734
1786
  const world = {
1735
- happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => `${cue.names.join(" and ")} noticed: ${cue.text}`)]),
1787
+ happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
1788
+ names: cue.names.join(tr(" and ")),
1789
+ text: cue.text
1790
+ }))]),
1736
1791
  beats: store.pendingBeats(),
1737
1792
  upcoming: store.upcoming(payload.turn)
1738
1793
  };
@@ -1753,6 +1808,7 @@ function installHooks(ctx, deps) {
1753
1808
  at: (locationId) => store.itemsAt(locationId, true),
1754
1809
  carried: (characterId) => store.carried(characterId)
1755
1810
  },
1811
+ language: store.settings().prompts.language,
1756
1812
  ...queryVector === void 0 ? {} : { queryVector }
1757
1813
  })];
1758
1814
  const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
@@ -1821,11 +1877,22 @@ function characterRunner(deps) {
1821
1877
  tools,
1822
1878
  maxCalls: deps.store.settings().memory.lookupCalls,
1823
1879
  result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
1824
- unenforced: ["thought"]
1880
+ unenforced: ["thought"],
1881
+ beforeSubmit: (value) => spokenIn(settings.prompts.language, value)
1825
1882
  });
1826
1883
  return parseCharacterAction(result);
1827
1884
  };
1828
1885
  }
1886
+ /** A character whose sheet is in another language than the chat's writes in the sheet's: the answer is refused until it is in the chat's. */
1887
+ function spokenIn(language, value) {
1888
+ const given = value;
1889
+ return wrongLanguage(language, {
1890
+ thought: given.thought,
1891
+ intent: given.intent,
1892
+ utterance: given.utterance,
1893
+ account: given.account
1894
+ });
1895
+ }
1829
1896
  /** What the character was reminded of and why, for the run's record, when the recall said why. */
1830
1897
  function recalledOf(request) {
1831
1898
  const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
@@ -1974,6 +2041,9 @@ const RESULT = {
1974
2041
  }
1975
2042
  }
1976
2043
  };
2044
+ /** A scaffold is about two dozen short texts: premise, hook, developments with their guidance, stakes and resolutions. */
2045
+ const PLOT_TEXTS = 24;
2046
+ const PLOT_TEXT_CHARS = 300;
1977
2047
  async function authorPlot(parent, store, turn, signal) {
1978
2048
  const cast = store.cast().map((member) => `${member.character.name} (${member.key}): ${member.character.summary}`).join("\n");
1979
2049
  const factions = store.story.factions.list().map((faction) => `${faction.name} (${faction.sourceId ?? faction.id}): ${faction.summary}`).join("\n");
@@ -1983,7 +2053,7 @@ async function authorPlot(parent, store, turn, signal) {
1983
2053
  const result = await runChild({
1984
2054
  parent,
1985
2055
  signal,
1986
- sampling: childSampling(store.settings(), "authoring"),
2056
+ sampling: childSampling(store.settings(), "authoring", estimateAnswer(Array.from({ length: PLOT_TEXTS }, () => PLOT_TEXT_CHARS), store.settings().prompts.language)),
1987
2057
  ...childModel(store.settings(), "authoring"),
1988
2058
  trace: childTrace(store, "authoring", "plot author"),
1989
2059
  persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
@@ -3026,11 +3096,94 @@ var AfterTurnJobs = class {
3026
3096
  }));
3027
3097
  }
3028
3098
  };
3099
+ /**
3100
+ * What the characters away from the player decide about what fell due, one commitment after another: their activity, and a move to where the commitment was when they
3101
+ * mean to keep it. It is recorded as a round only they perceive, and the keeper writes it.
3102
+ */
3103
+ async function runOffScene(deps, owner, state, store, due, limit) {
3104
+ const { summary, perCharacter, joint } = store.settings().offstage;
3105
+ let budget = limit;
3106
+ const acted = /* @__PURE__ */ new Map();
3107
+ for (const item of due) {
3108
+ if (budget <= 0) break;
3109
+ const cast = store.cast();
3110
+ const keys = item.characters.filter((key) => cast.some((member) => member.key === key) && (acted.get(key) ?? 0) < perCharacter).slice(0, budget);
3111
+ if (keys.length === 0) continue;
3112
+ budget -= keys.length;
3113
+ for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
3114
+ const reports = [];
3115
+ for (const group of joint ? keys.map((key) => [key]) : [keys]) {
3116
+ const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
3117
+ const asked = {
3118
+ ...state,
3119
+ situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
3120
+ history: [],
3121
+ recalled: /* @__PURE__ */ new Map()
3122
+ };
3123
+ delete asked.first;
3124
+ delete asked.second;
3125
+ reports.push(...(await deps.ask(group, cast, asked, summary)).reports);
3126
+ }
3127
+ if (reports.length === 0) continue;
3128
+ const where = item.place;
3129
+ const moves = new Map(reports.flatMap((report) => {
3130
+ if (report.commitment === "low" || where === void 0) return [];
3131
+ const check = store.checkMove(report.character, {
3132
+ location: where,
3133
+ ignoreExits: true
3134
+ });
3135
+ return check.ok ? [[report.character, check]] : [];
3136
+ }));
3137
+ store.commit(reports.flatMap((report) => {
3138
+ const member = cast.find((candidate) => candidate.key === report.character);
3139
+ const move = moves.get(report.character);
3140
+ return member === void 0 ? [] : [{
3141
+ character: member.character.id,
3142
+ patch: { activity: report.intent },
3143
+ ...move?.ok === true ? { move: move.move } : {}
3144
+ }];
3145
+ }));
3146
+ state.offstage += 1;
3147
+ const time = store.time(owner.turn);
3148
+ store.queueCommit({
3149
+ turn: owner.turn,
3150
+ round: 100 + state.offstage,
3151
+ situation: item.text,
3152
+ offstage: true,
3153
+ time: {
3154
+ from: time.now,
3155
+ to: time.now,
3156
+ zone: time.zone
3157
+ },
3158
+ entries: reports.map((report) => {
3159
+ const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
3160
+ const move = moves.get(report.character);
3161
+ return {
3162
+ character: report.character,
3163
+ name: report.name,
3164
+ intent: report.intent,
3165
+ commitment: report.commitment,
3166
+ result: "succeeded",
3167
+ summary: report.intent,
3168
+ spoken: false,
3169
+ ...at === void 0 ? {} : { at: {
3170
+ key: locationKey(at),
3171
+ name: at.name
3172
+ } },
3173
+ ...move?.ok === true && move.plan.from !== move.move.to ? { moved: { ...move.to } } : {}
3174
+ };
3175
+ })
3176
+ });
3177
+ store.markHandled([item.key]);
3178
+ deps.write();
3179
+ if (summary && deps.stillThis()) {
3180
+ const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3181
+ store.addNote("away", owner.turn, lines);
3182
+ }
3183
+ }
3184
+ }
3029
3185
  //#endregion
3030
- //#region src/host/orchestration/turn-engine.ts
3031
- const MAX_OBJECTIONS = 3;
3032
- /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
3033
- const MAX_ROUND_SECONDS = 86400;
3186
+ //#region src/host/orchestration/turn-text.ts
3034
3187
  /**
3035
3188
  * A model sometimes sends who speaks as a segment of its own (an utterance with no character whose text is the character's key or name) followed by the words with no
3036
3189
  * character either. When the label is exactly a character of the scene, the label is folded into the words that follow it.
@@ -3079,6 +3232,162 @@ function repeatsEarlier(signature, asked) {
3079
3232
  return union === 0 || shared / union >= SAME_SITUATION;
3080
3233
  });
3081
3234
  }
3235
+ /** The words as the character said them, whatever quotes the game master put around them. */
3236
+ function asSpoken(segments, spoken) {
3237
+ const left = [...spoken];
3238
+ return segments.map((segment) => {
3239
+ if (segment.type !== "utterance") return segment;
3240
+ const at = left.findIndex((said) => said.character === segment.character && sameWords(said.text, segment.text));
3241
+ return at === -1 ? segment : {
3242
+ ...segment,
3243
+ text: left.splice(at, 1)[0].text
3244
+ };
3245
+ });
3246
+ }
3247
+ //#endregion
3248
+ //#region src/host/orchestration/turn-rules.ts
3249
+ /** Whether the game master still has to judge the player's action. */
3250
+ function judgeDue(state) {
3251
+ return state.judgeWanted === true && state.phase === "idle" && state.ooc === void 0 && state.judgement === void 0;
3252
+ }
3253
+ /** Why an out-of-character command may not change anything yet, when it may not. */
3254
+ function oocBlock(state) {
3255
+ if (state.ooc === void 0) return void 0;
3256
+ if (state.ooc.question === true) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3257
+ if (state.ooc.ruling === void 0) return "this turn is an out-of-character command: rule on it first with ooc_ruling";
3258
+ return state.ooc.ruling.legal ? void 0 : "the command was refused: nothing changes; call narrate with no segments to tell the player";
3259
+ }
3260
+ /** Whether the chat wants a preview of the scene and the game master has not shown it yet. */
3261
+ function previewDue(state) {
3262
+ return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
3263
+ }
3264
+ function explainPhase(state, attempted) {
3265
+ if (state.ooc?.question === true && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3266
+ if (state.ooc !== void 0 && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character command: rule on it first with ooc_ruling" : state.ooc.ruling.legal ? "make the command happen with resolve_round, expand_world or advance_time, then call narrate with what the player perceives (narration only)" : "the command was refused: call narrate with no segments";
3267
+ const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
3268
+ switch (state.phase) {
3269
+ case "idle": return judgeDue(state) ? "call judge_action first: does what the player's character tries work? It does not when it is not viable or it breaks a rule of the world or of the player" : previewDue(state) ? "call preview_scene first: two or three sentences that show the player how the scene opens, before the characters are asked" : state.judgement?.allowed === false && attempted !== "activate_characters" ? `the attempt does not work (${state.judgement.reason}): call resolve_round with one outcome, for the player's character only (result failed, a sentence on what it does and why nothing comes of it)${attempted === "narrate" ? ", then narrate" : ""}` : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : attempted === "narrate" ? "nothing to deliver yet: call activate_characters to let the characters act, or, when nobody else needs to react, call resolve_round with an outcome for the player's character alone, and then narrate" : "nothing to resolve yet: call activate_characters first";
3270
+ case "resolving": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round with one outcome for each of: ${waiting(state.first)}` : `call resolve_round with one outcome for each of: ${waiting(state.first)}`;
3271
+ case "retrying": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round once more, with one outcome for each of: ${waiting(state.second)}` : `call resolve_round once more, with one outcome for each of: ${waiting(state.second)}`;
3272
+ case "between": return attempted === "resolve_round" ? "the round is already recorded: call activate_characters again if the story needs it, or narrate" : `call narrate with the output of the turn${mustSay(state)}${canContinue(state)}`;
3273
+ case "done": return "this turn is already recorded";
3274
+ case "skipped": return "this turn needs no round";
3275
+ }
3276
+ }
3277
+ function canContinue(state) {
3278
+ const left = (state.limit ?? 0) - state.rounds;
3279
+ return left > 0 ? `, or call activate_characters if the story genuinely needs them again (${left} round(s) left)` : "";
3280
+ }
3281
+ function mustSay(state) {
3282
+ return state.utterances.length === 0 ? "" : `; it must carry these utterances exactly, in this order: ${state.utterances.map((utterance) => `${utterance.name}: "${utterance.text}"`).join(" | ")}`;
3283
+ }
3284
+ /** `player` is the key of the player's character when an outcome for it is acceptable: it is not asked to act, but what it did can move it or have it handle things. */
3285
+ function checkOutcomes(attempt, outcomes, store, player, decreed) {
3286
+ const expected = decreed === void 0 ? attempt.reports.map((report) => report.character) : [...new Set(outcomes.map((outcome) => outcome.character))];
3287
+ const unknown = decreed === void 0 ? [] : [...new Set(outcomes.map((outcome) => outcome.character))].filter((key) => !decreed.some((member) => member.key === key)).map((key) => `${key} is not a character of the story`);
3288
+ const given = outcomes.filter((outcome) => outcome.character !== player).map((outcome) => outcome.character);
3289
+ const problems = [
3290
+ ...unknown,
3291
+ ...outcomes.filter((outcome) => outcome.character === player).length > 1 ? [`more than one outcome for ${player}`] : [],
3292
+ ...expected.filter((key) => !given.includes(key)).map((key) => `missing an outcome for ${key}`),
3293
+ ...[...new Set(given.filter((key) => !expected.includes(key)))].map((key) => `${key} is not waiting for an outcome`),
3294
+ ...[...new Set(given.filter((key, index) => given.indexOf(key) !== index))].map((key) => `more than one outcome for ${key}`),
3295
+ ...outcomes.filter((outcome) => !RESULTS.includes(outcome.result)).map((outcome) => `${outcome.character}: unknown result "${outcome.result}"`),
3296
+ ...outcomes.filter((outcome) => outcome.summary.trim() === "").map((outcome) => `${outcome.character}: say what happens`),
3297
+ ...outcomes.flatMap((outcome) => moveProblems(outcome, store)),
3298
+ ...itemProblems(outcomes, store),
3299
+ ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`))
3300
+ ];
3301
+ if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} (expected exactly: ${expected.join(", ")})`);
3302
+ }
3303
+ /** Why a character cannot go where the outcome sends it, if it cannot: the game master hears it before the round is recorded. */
3304
+ function moveProblems(outcome, store) {
3305
+ if (outcome.moveTo === void 0) return [];
3306
+ if (outcome.result === "failed") return [`${outcome.character}: its intent failed, so it does not go anywhere: leave moves_to out`];
3307
+ const checked = store.checkMove(outcome.character, outcome.moveTo);
3308
+ return checked.ok ? [] : checked.problems.map((problem) => `${outcome.character}: cannot go to ${outcome.moveTo?.location}: ${problem}`);
3309
+ }
3310
+ /** Why what the outcomes do with things cannot be done, if it cannot: tried in order, each seeing what the one before did. */
3311
+ function itemProblems(outcomes, store) {
3312
+ const entries = outcomes.flatMap((outcome) => outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 || outcome.result === "failed" ? [] : [{
3313
+ character: outcome.character,
3314
+ changes: outcome.itemChanges
3315
+ }]);
3316
+ const failed = outcomes.filter((outcome) => outcome.result === "failed" && (outcome.itemChanges?.length ?? 0) > 0).map((outcome) => `${outcome.character}: its intent failed, so it does nothing with things: leave item_changes out`);
3317
+ if (entries.length === 0) return failed;
3318
+ const checked = store.checkItemChanges(entries);
3319
+ return checked.ok ? failed : [...failed, ...checked.problems];
3320
+ }
3321
+ /** What the world made a character notice: taken up in the first attempt of a round, and told the same again on the retry. */
3322
+ function cuesOf(state, key, member, store, attempt) {
3323
+ if (attempt === 2 || store === void 0) return state.cues.get(key) ?? [];
3324
+ const pending = store.cuesFor(member.character.id);
3325
+ if (pending.length === 0) return [];
3326
+ store.doneCues(pending.map((cue) => cue.id));
3327
+ const texts = pending.map((cue) => cue.text);
3328
+ state.cues.set(key, texts);
3329
+ return texts;
3330
+ }
3331
+ /** How a character sees people present or explicitly in the moment, for those it has a profile of. */
3332
+ function knownRelationships(member, company, situation, cast, store) {
3333
+ const present = new Set(company.map((candidate) => candidate.character.id));
3334
+ const relevant = mentioned(situation, cast.map((candidate) => candidate.character));
3335
+ return store.story.relationships.from(member.character.id).flatMap((relation) => {
3336
+ if (!present.has(relation.toId) && !relevant.has(relation.toId)) return [];
3337
+ const other = cast.find((candidate) => candidate.character.id === relation.toId);
3338
+ return other === void 0 || other.key === member.key ? [] : [{
3339
+ name: referent(other.character),
3340
+ label: relation.label,
3341
+ summary: relation.summary,
3342
+ present: present.has(relation.toId),
3343
+ familiarity: relation.familiarity,
3344
+ trust: relation.trust,
3345
+ affinity: relation.affinity,
3346
+ tension: relation.tension
3347
+ }];
3348
+ });
3349
+ }
3350
+ function reactions(state) {
3351
+ const first = state.first;
3352
+ return (first?.outcomes ?? []).flatMap((outcome) => {
3353
+ const report = first?.reports.find((candidate) => candidate.character === outcome.character);
3354
+ return report === void 0 ? [] : [{
3355
+ character: report.character,
3356
+ name: report.name,
3357
+ intent: report.intent,
3358
+ ...report.utterance === void 0 ? {} : { utterance: report.utterance },
3359
+ result: outcome.result,
3360
+ summary: outcome.summary
3361
+ }];
3362
+ });
3363
+ }
3364
+ /** The final decision for each character of the round: the retry's replaces the first attempt's. */
3365
+ /** The player's character is never asked to act, so what the game master decided it did stands in for its report. */
3366
+ function playerReport(state, outcome) {
3367
+ const member = state.cast.find((candidate) => candidate.key === outcome.character && candidate.character.control === "player");
3368
+ return member === void 0 ? void 0 : {
3369
+ character: member.key,
3370
+ name: member.character.name,
3371
+ intent: outcome.summary,
3372
+ commitment: "high"
3373
+ };
3374
+ }
3375
+ function decisions(state) {
3376
+ const decided = /* @__PURE__ */ new Map();
3377
+ for (const attempt of [state.first, state.second]) for (const outcome of attempt?.outcomes ?? []) {
3378
+ const report = attempt?.reports.find((candidate) => candidate.character === outcome.character) ?? playerReport(state, outcome);
3379
+ if (report !== void 0) decided.set(outcome.character, {
3380
+ outcome,
3381
+ report
3382
+ });
3383
+ }
3384
+ return decided;
3385
+ }
3386
+ //#endregion
3387
+ //#region src/host/orchestration/turn-engine.ts
3388
+ const MAX_OBJECTIONS = 3;
3389
+ /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
3390
+ const MAX_ROUND_SECONDS = 86400;
3082
3391
  /** The game master is asked to correct its output this many times before it is corrected for it. */
3083
3392
  const MAX_REFUSALS = 2;
3084
3393
  /** The runs of the record keeper that may fail one after another before the rounds waiting for it are given up, so that they cannot pile up for ever. */
@@ -3178,7 +3487,7 @@ var TurnEngine = class {
3178
3487
  }, store.story, signal);
3179
3488
  const place = member.place === void 0 ? void 0 : store.place(member.place.location.id);
3180
3489
  const company = place === void 0 ? cast : place.here;
3181
- const relationships = this.knownRelationships(member, company, question, cast, store);
3490
+ const relationships = knownRelationships(member, company, question, cast, store);
3182
3491
  const carrying = store.carried(member.character.id);
3183
3492
  const affiliations = store.affiliations(member.character.id);
3184
3493
  const tracked = store.trackedFor(member.character.id, company.map((entry) => entry.character.id));
@@ -3262,17 +3571,6 @@ var TurnEngine = class {
3262
3571
  expectJudgement(owner) {
3263
3572
  this.stateFor(owner).judgeWanted = true;
3264
3573
  }
3265
- /** Whether the game master still has to judge the player's action. */
3266
- judgeDue(state) {
3267
- return state.judgeWanted === true && state.phase === "idle" && state.ooc === void 0 && state.judgement === void 0;
3268
- }
3269
- /** Why an out-of-character command may not change anything yet, when it may not. */
3270
- oocBlock(state) {
3271
- if (state.ooc === void 0) return void 0;
3272
- if (state.ooc.question === true) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3273
- if (state.ooc.ruling === void 0) return "this turn is an out-of-character command: rule on it first with ooc_ruling";
3274
- return state.ooc.ruling.legal ? void 0 : "the command was refused: nothing changes; call narrate with no segments to tell the player";
3275
- }
3276
3574
  /** Mark a turn as one that needs no round, for example because the player's input was refused. */
3277
3575
  skip(owner) {
3278
3576
  this.stateFor(owner).phase = "skipped";
@@ -3284,10 +3582,10 @@ var TurnEngine = class {
3284
3582
  async activate(owner, input, run, signal) {
3285
3583
  const state = this.stateFor(owner);
3286
3584
  if (state.ooc !== void 0) throw new Error(state.ooc.question === true ? "a question asks nobody to act and changes nothing: answer it with ooc_answer" : "an out-of-character command asks nobody to act: decree what happens with resolve_round, or narrate");
3287
- if (state.phase !== "idle" && state.phase !== "between") throw new Error(this.explain(state, "activate_characters"));
3288
- if (this.judgeDue(state)) throw new Error(this.explain(state, "activate_characters"));
3585
+ if (state.phase !== "idle" && state.phase !== "between") throw new Error(explainPhase(state, "activate_characters"));
3586
+ if (judgeDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3289
3587
  if (state.judgement?.allowed === false && state.rounds === 0) throw new Error(`the action cannot work (${state.judgement.reason}): nobody is asked to act on it. Play the failed attempt with resolve_round: one outcome for the player's character, result failed`);
3290
- if (this.previewDue(state)) throw new Error(this.explain(state, "activate_characters"));
3588
+ if (previewDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3291
3589
  const store = this.storeOf(owner);
3292
3590
  const limit = store.settings().maxRounds;
3293
3591
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} of characters were already played for this message, which is the most this chat allows: deliver the output with narrate`);
@@ -3334,14 +3632,14 @@ var TurnEngine = class {
3334
3632
  const store = this.storeOf(owner);
3335
3633
  if (state.ooc !== void 0) return { done: this.decree(owner, state, outcomes, elapsedSeconds) };
3336
3634
  if (state.phase === "idle" || state.phase === "between") {
3337
- if (this.judgeDue(state) || this.previewDue(state)) throw new Error(this.explain(state, "resolve_round"));
3635
+ if (judgeDue(state) || previewDue(state)) throw new Error(explainPhase(state, "resolve_round"));
3338
3636
  const player = store.cast().find((member) => member.character.control === "player");
3339
3637
  if (player !== void 0 && outcomes.length === 1 && outcomes[0]?.character === player.key) return { done: this.resolvePlayer(owner, state, outcomes[0], elapsedSeconds) };
3340
3638
  }
3341
- if (state.phase !== "resolving" && state.phase !== "retrying") throw new Error(this.explain(state, "resolve_round"));
3639
+ if (state.phase !== "resolving" && state.phase !== "retrying") throw new Error(explainPhase(state, "resolve_round"));
3342
3640
  const attempt = state.phase === "resolving" ? state.first : state.second;
3343
3641
  if (attempt === void 0) throw new Error("internal: no round to resolve");
3344
- this.check(attempt, outcomes, store, state.phase === "resolving" ? this.playerKey(state) : void 0);
3642
+ checkOutcomes(attempt, outcomes, store, state.phase === "resolving" ? this.playerKey(state) : void 0);
3345
3643
  if (elapsedSeconds !== void 0) state.elapsed = this.elapsedChecked(owner, elapsedSeconds);
3346
3644
  attempt.outcomes = [...outcomes];
3347
3645
  if (state.phase === "resolving") {
@@ -3371,14 +3669,14 @@ var TurnEngine = class {
3371
3669
  * @throws {Error} when the command was not ruled legal, the limit of rounds is reached, or an outcome is not acceptable.
3372
3670
  */
3373
3671
  decree(owner, state, outcomes, elapsedSeconds) {
3374
- const blocked = this.oocBlock(state);
3672
+ const blocked = oocBlock(state);
3375
3673
  if (blocked !== void 0) throw new Error(blocked);
3376
3674
  const store = this.storeOf(owner);
3377
3675
  const limit = store.settings().maxRounds;
3378
3676
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} were already decreed for this command, which is the most this chat allows: deliver the output with narrate`);
3379
3677
  state.cast = store.cast();
3380
3678
  if (outcomes.length === 0) throw new Error("decree at least one outcome");
3381
- this.check({
3679
+ checkOutcomes({
3382
3680
  reports: [],
3383
3681
  failures: []
3384
3682
  }, outcomes, store, void 0, state.cast);
@@ -3417,7 +3715,7 @@ var TurnEngine = class {
3417
3715
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} were already played for this message, which is the most this chat allows: deliver the output with narrate`);
3418
3716
  state.cast = store.cast();
3419
3717
  const player = state.cast.find((member) => member.key === outcome.character);
3420
- this.check({
3718
+ checkOutcomes({
3421
3719
  reports: [],
3422
3720
  failures: []
3423
3721
  }, [outcome], store, outcome.character);
@@ -3440,7 +3738,7 @@ var TurnEngine = class {
3440
3738
  preview(owner, text) {
3441
3739
  const state = this.stateFor(owner);
3442
3740
  if (state.ooc !== void 0) throw new Error("an out-of-character turn shows no preview: go on with " + (state.ooc.question === true ? "ooc_answer" : "ooc_ruling"));
3443
- if (this.judgeDue(state)) throw new Error("judge the action first with judge_action");
3741
+ if (judgeDue(state)) throw new Error("judge the action first with judge_action");
3444
3742
  if (!this.storeOf(owner).settings().preview.enabled) throw new Error("this chat shows no preview: go on with activate_characters");
3445
3743
  if (state.previewed) throw new Error("a preview was already shown for this message: go on with activate_characters");
3446
3744
  if (state.phase !== "idle") throw new Error("the preview comes first, before the characters are asked");
@@ -3476,8 +3774,8 @@ var TurnEngine = class {
3476
3774
  advanceTime(owner, request) {
3477
3775
  const state = this.stateFor(owner);
3478
3776
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: time is skipped between rounds, not in the middle of one");
3479
- if (state.phase === "done" || state.phase === "skipped") throw new Error(this.explain(state, void 0));
3480
- const blocked = this.oocBlock(state);
3777
+ if (state.phase === "done" || state.phase === "skipped") throw new Error(explainPhase(state, void 0));
3778
+ const blocked = oocBlock(state);
3481
3779
  if (blocked !== void 0) throw new Error(blocked);
3482
3780
  try {
3483
3781
  return {
@@ -3497,7 +3795,7 @@ var TurnEngine = class {
3497
3795
  */
3498
3796
  async narrate(owner, segments, run, addressed = []) {
3499
3797
  const state = this.stateFor(owner);
3500
- if (state.phase !== "between") throw new Error(this.explain(state, "narrate"));
3798
+ if (state.phase !== "between") throw new Error(explainPhase(state, "narrate"));
3501
3799
  const pending = new Set(this.storeOf(owner).pendingBeats().map((beat) => beat.id));
3502
3800
  const unknown = addressed.filter((id) => !pending.has(id));
3503
3801
  if (unknown.length > 0) throw new Error(`addressed: ${unknown.join(", ")} ${unknown.length === 1 ? "is" : "are"} not ${unknown.length === 1 ? "a beat" : "beats"} still to weave in (the scene lists them)`);
@@ -3541,7 +3839,7 @@ var TurnEngine = class {
3541
3839
  async expand(owner, input, signal) {
3542
3840
  const state = this.stateFor(owner);
3543
3841
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: the world is extended between rounds, not in the middle of one");
3544
- const blocked = this.oocBlock(state);
3842
+ const blocked = oocBlock(state);
3545
3843
  if (blocked !== void 0) throw new Error(blocked);
3546
3844
  const need = AUTHORING_NEEDS.find((candidate) => candidate === input.need);
3547
3845
  if (need === void 0) throw new Error(`"${input.need}" is not a reason to make something up; the reasons are: ${AUTHORING_NEEDS.join(", ")}`);
@@ -3568,7 +3866,7 @@ var TurnEngine = class {
3568
3866
  introduce(owner, input) {
3569
3867
  const state = this.stateFor(owner);
3570
3868
  if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: things are introduced between rounds, not in the middle of one");
3571
- const blocked = this.oocBlock(state);
3869
+ const blocked = oocBlock(state);
3572
3870
  if (blocked !== void 0) throw new Error(blocked);
3573
3871
  const name = input.name.trim();
3574
3872
  if (name === "") throw new Error("name the thing");
@@ -3630,93 +3928,20 @@ var TurnEngine = class {
3630
3928
  this.offstage.delete(owner.chat);
3631
3929
  }));
3632
3930
  }
3633
- async runOffScene(owner, state, store, due, limit, run) {
3634
- const { summary, perCharacter, joint } = store.settings().offstage;
3635
- let budget = limit;
3636
- const acted = /* @__PURE__ */ new Map();
3637
- for (const item of due) {
3638
- if (budget <= 0) break;
3639
- const cast = store.cast();
3640
- const keys = item.characters.filter((key) => cast.some((member) => member.key === key) && (acted.get(key) ?? 0) < perCharacter).slice(0, budget);
3641
- if (keys.length === 0) continue;
3642
- budget -= keys.length;
3643
- for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
3644
- const reports = [];
3645
- for (const group of joint ? keys.map((key) => [key]) : [keys]) {
3646
- const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
3647
- const asked = {
3648
- ...state,
3649
- situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
3650
- history: [],
3651
- recalled: /* @__PURE__ */ new Map()
3652
- };
3653
- delete asked.first;
3654
- delete asked.second;
3655
- reports.push(...(await this.runAttempt(owner, 1, group, cast, asked, run, state.cancel.signal, summary)).reports);
3656
- }
3657
- if (reports.length === 0) continue;
3658
- const where = item.place;
3659
- const moves = new Map(reports.flatMap((report) => {
3660
- if (report.commitment === "low" || where === void 0) return [];
3661
- const check = store.checkMove(report.character, {
3662
- location: where,
3663
- ignoreExits: true
3664
- });
3665
- return check.ok ? [[report.character, check]] : [];
3666
- }));
3667
- store.commit(reports.flatMap((report) => {
3668
- const member = cast.find((candidate) => candidate.key === report.character);
3669
- const move = moves.get(report.character);
3670
- return member === void 0 ? [] : [{
3671
- character: member.character.id,
3672
- patch: { activity: report.intent },
3673
- ...move?.ok === true ? { move: move.move } : {}
3674
- }];
3675
- }));
3676
- state.offstage += 1;
3677
- const time = store.time(owner.turn);
3678
- store.queueCommit({
3679
- turn: owner.turn,
3680
- round: 100 + state.offstage,
3681
- situation: item.text,
3682
- offstage: true,
3683
- time: {
3684
- from: time.now,
3685
- to: time.now,
3686
- zone: time.zone
3687
- },
3688
- entries: reports.map((report) => {
3689
- const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
3690
- const move = moves.get(report.character);
3691
- return {
3692
- character: report.character,
3693
- name: report.name,
3694
- intent: report.intent,
3695
- commitment: report.commitment,
3696
- result: "succeeded",
3697
- summary: report.intent,
3698
- spoken: false,
3699
- ...at === void 0 ? {} : { at: {
3700
- key: locationKey(at),
3701
- name: at.name
3702
- } },
3703
- ...move?.ok === true && move.plan.from !== move.move.to ? { moved: { ...move.to } } : {}
3704
- };
3705
- })
3706
- });
3707
- store.markHandled([item.key]);
3708
- this.write(owner, state);
3709
- if (summary && this.states.get(owner.chat) === state) {
3710
- const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3711
- store.addNote("away", owner.turn, lines);
3712
- }
3713
- }
3931
+ runOffScene(owner, state, store, due, limit, run) {
3932
+ return runOffScene({
3933
+ ask: (group, cast, asked, summary) => this.runAttempt(owner, 1, group, cast, asked, run, state.cancel.signal, summary),
3934
+ write: () => {
3935
+ this.write(owner, state);
3936
+ },
3937
+ stillThis: () => this.states.get(owner.chat) === state
3938
+ }, owner, state, store, due, limit);
3714
3939
  }
3715
3940
  /** What still has to happen before the turn may end, or nothing when it may. */
3716
3941
  missing(owner) {
3717
3942
  const state = this.stateFor(owner);
3718
3943
  if (state.phase === "done" || state.phase === "skipped") return void 0;
3719
- return this.explain(state, void 0);
3944
+ return explainPhase(state, void 0);
3720
3945
  }
3721
3946
  /** Wait until the records being written are written or have failed. */
3722
3947
  async flush(owner) {
@@ -3854,72 +4079,11 @@ var TurnEngine = class {
3854
4079
  if (store === void 0) throw new Error("this chat is not a roleplay session");
3855
4080
  return store;
3856
4081
  }
3857
- /** Whether the chat wants a preview of the scene and the game master has not shown it yet. */
3858
- previewDue(state) {
3859
- return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
3860
- }
3861
- explain(state, attempted) {
3862
- if (state.ooc?.question === true && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3863
- if (state.ooc !== void 0 && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character command: rule on it first with ooc_ruling" : state.ooc.ruling.legal ? "make the command happen with resolve_round, expand_world or advance_time, then call narrate with what the player perceives (narration only)" : "the command was refused: call narrate with no segments";
3864
- const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
3865
- switch (state.phase) {
3866
- case "idle": return this.judgeDue(state) ? "call judge_action first: does what the player's character tries work? It does not when it is not viable or it breaks a rule of the world or of the player" : this.previewDue(state) ? "call preview_scene first: two or three sentences that show the player how the scene opens, before the characters are asked" : state.judgement?.allowed === false && attempted !== "activate_characters" ? `the attempt does not work (${state.judgement.reason}): call resolve_round with one outcome, for the player's character only (result failed, a sentence on what it does and why nothing comes of it)${attempted === "narrate" ? ", then narrate" : ""}` : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : attempted === "narrate" ? "nothing to deliver yet: call activate_characters to let the characters act, or, when nobody else needs to react, call resolve_round with an outcome for the player's character alone, and then narrate" : "nothing to resolve yet: call activate_characters first";
3867
- case "resolving": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round with one outcome for each of: ${waiting(state.first)}` : `call resolve_round with one outcome for each of: ${waiting(state.first)}`;
3868
- case "retrying": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round once more, with one outcome for each of: ${waiting(state.second)}` : `call resolve_round once more, with one outcome for each of: ${waiting(state.second)}`;
3869
- case "between": return attempted === "resolve_round" ? "the round is already recorded: call activate_characters again if the story needs it, or narrate" : `call narrate with the output of the turn${this.mustSay(state)}${this.canContinue(state)}`;
3870
- case "done": return "this turn is already recorded";
3871
- case "skipped": return "this turn needs no round";
3872
- }
3873
- }
3874
- canContinue(state) {
3875
- const left = (state.limit ?? 0) - state.rounds;
3876
- return left > 0 ? `, or call activate_characters if the story genuinely needs them again (${left} round(s) left)` : "";
3877
- }
3878
- mustSay(state) {
3879
- return state.utterances.length === 0 ? "" : `; it must carry these utterances exactly, in this order: ${state.utterances.map((utterance) => `${utterance.name}: "${utterance.text}"`).join(" | ")}`;
3880
- }
3881
- /** `player` is the key of the player's character when an outcome for it is acceptable: it is not asked to act, but what it did can move it or have it handle things. */
3882
- check(attempt, outcomes, store, player, decreed) {
3883
- const expected = decreed === void 0 ? attempt.reports.map((report) => report.character) : [...new Set(outcomes.map((outcome) => outcome.character))];
3884
- const unknown = decreed === void 0 ? [] : [...new Set(outcomes.map((outcome) => outcome.character))].filter((key) => !decreed.some((member) => member.key === key)).map((key) => `${key} is not a character of the story`);
3885
- const given = outcomes.filter((outcome) => outcome.character !== player).map((outcome) => outcome.character);
3886
- const problems = [
3887
- ...unknown,
3888
- ...outcomes.filter((outcome) => outcome.character === player).length > 1 ? [`more than one outcome for ${player}`] : [],
3889
- ...expected.filter((key) => !given.includes(key)).map((key) => `missing an outcome for ${key}`),
3890
- ...[...new Set(given.filter((key) => !expected.includes(key)))].map((key) => `${key} is not waiting for an outcome`),
3891
- ...[...new Set(given.filter((key, index) => given.indexOf(key) !== index))].map((key) => `more than one outcome for ${key}`),
3892
- ...outcomes.filter((outcome) => !RESULTS.includes(outcome.result)).map((outcome) => `${outcome.character}: unknown result "${outcome.result}"`),
3893
- ...outcomes.filter((outcome) => outcome.summary.trim() === "").map((outcome) => `${outcome.character}: say what happens`),
3894
- ...outcomes.flatMap((outcome) => this.moveProblems(outcome, store)),
3895
- ...this.itemProblems(outcomes, store),
3896
- ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`))
3897
- ];
3898
- if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} (expected exactly: ${expected.join(", ")})`);
3899
- }
3900
- /** Why a character cannot go where the outcome sends it, if it cannot: the game master hears it before the round is recorded. */
3901
- moveProblems(outcome, store) {
3902
- if (outcome.moveTo === void 0) return [];
3903
- if (outcome.result === "failed") return [`${outcome.character}: its intent failed, so it does not go anywhere: leave moves_to out`];
3904
- const checked = store.checkMove(outcome.character, outcome.moveTo);
3905
- return checked.ok ? [] : checked.problems.map((problem) => `${outcome.character}: cannot go to ${outcome.moveTo?.location}: ${problem}`);
3906
- }
3907
- /** Why what the outcomes do with things cannot be done, if it cannot: tried in order, each seeing what the one before did. */
3908
- itemProblems(outcomes, store) {
3909
- const entries = outcomes.flatMap((outcome) => outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 || outcome.result === "failed" ? [] : [{
3910
- character: outcome.character,
3911
- changes: outcome.itemChanges
3912
- }]);
3913
- const failed = outcomes.filter((outcome) => outcome.result === "failed" && (outcome.itemChanges?.length ?? 0) > 0).map((outcome) => `${outcome.character}: its intent failed, so it does nothing with things: leave item_changes out`);
3914
- if (entries.length === 0) return failed;
3915
- const checked = store.checkItemChanges(entries);
3916
- return checked.ok ? failed : [...failed, ...checked.problems];
3917
- }
3918
4082
  /** Every character acts at the same time; one that fails or answers badly is reported, not fatal. */
3919
4083
  async runAttempt(owner, number, keys, cast, state, run, signal, away = false) {
3920
4084
  const store = this.stores(owner.chat);
3921
4085
  const { outputValidator } = this.boundaries();
3922
- const reaction = number === 2 ? this.reactions(state) : void 0;
4086
+ const reaction = number === 2 ? reactions(state) : void 0;
3923
4087
  const queryVector = number === 1 && store !== void 0 ? await store.queryVector(state.situation, signal) : void 0;
3924
4088
  const time = store?.time(owner.turn);
3925
4089
  const answers = await Promise.all(keys.map(async (key) => {
@@ -3940,12 +4104,12 @@ var TurnEngine = class {
3940
4104
  }, store.story, signal) : state.recalled.get(key) ?? [];
3941
4105
  if (number === 1 && memories.length > 0) state.recalled.set(key, memories);
3942
4106
  const place = member.place === void 0 ? void 0 : store?.place(member.place.location.id);
3943
- const relationships = store === void 0 ? [] : this.knownRelationships(member, place === void 0 ? cast : place.here, state.situation, cast, store);
4107
+ const relationships = store === void 0 ? [] : knownRelationships(member, place === void 0 ? cast : place.here, state.situation, cast, store);
3944
4108
  const carrying = store === void 0 ? [] : store.carried(member.character.id);
3945
4109
  const knowledge = store?.knowledge(member.character.id, owner.turn, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
3946
4110
  const affiliations = store?.affiliations(member.character.id) ?? [];
3947
4111
  const agenda = store?.agenda(owner.turn, member.character.id);
3948
- const cues = this.cuesOf(state, key, member, store, number);
4112
+ const cues = cuesOf(state, key, member, store, number);
3949
4113
  const upcoming = store?.upcomingFor(member.character.id, owner.turn) ?? [];
3950
4114
  const tracked = store?.trackedFor(member.character.id, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
3951
4115
  const request = {
@@ -4006,74 +4170,9 @@ var TurnEngine = class {
4006
4170
  failures: answers.filter((answer) => "reason" in answer)
4007
4171
  };
4008
4172
  }
4009
- /** What the world made a character notice: taken up in the first attempt of a round, and told the same again on the retry. */
4010
- cuesOf(state, key, member, store, attempt) {
4011
- if (attempt === 2 || store === void 0) return state.cues.get(key) ?? [];
4012
- const pending = store.cuesFor(member.character.id);
4013
- if (pending.length === 0) return [];
4014
- store.doneCues(pending.map((cue) => cue.id));
4015
- const texts = pending.map((cue) => cue.text);
4016
- state.cues.set(key, texts);
4017
- return texts;
4018
- }
4019
- /** How a character sees people present or explicitly in the moment, for those it has a profile of. */
4020
- knownRelationships(member, company, situation, cast, store) {
4021
- const present = new Set(company.map((candidate) => candidate.character.id));
4022
- const relevant = mentioned(situation, cast.map((candidate) => candidate.character));
4023
- return store.story.relationships.from(member.character.id).flatMap((relation) => {
4024
- if (!present.has(relation.toId) && !relevant.has(relation.toId)) return [];
4025
- const other = cast.find((candidate) => candidate.character.id === relation.toId);
4026
- return other === void 0 || other.key === member.key ? [] : [{
4027
- name: referent(other.character),
4028
- label: relation.label,
4029
- summary: relation.summary,
4030
- present: present.has(relation.toId),
4031
- familiarity: relation.familiarity,
4032
- trust: relation.trust,
4033
- affinity: relation.affinity,
4034
- tension: relation.tension
4035
- }];
4036
- });
4037
- }
4038
- reactions(state) {
4039
- const first = state.first;
4040
- return (first?.outcomes ?? []).flatMap((outcome) => {
4041
- const report = first?.reports.find((candidate) => candidate.character === outcome.character);
4042
- return report === void 0 ? [] : [{
4043
- character: report.character,
4044
- name: report.name,
4045
- intent: report.intent,
4046
- ...report.utterance === void 0 ? {} : { utterance: report.utterance },
4047
- result: outcome.result,
4048
- summary: outcome.summary
4049
- }];
4050
- });
4051
- }
4052
- /** The final decision for each character of the round: the retry's replaces the first attempt's. */
4053
- /** The player's character is never asked to act, so what the game master decided it did stands in for its report. */
4054
- playerReport(state, outcome) {
4055
- const member = state.cast.find((candidate) => candidate.key === outcome.character && candidate.character.control === "player");
4056
- return member === void 0 ? void 0 : {
4057
- character: member.key,
4058
- name: member.character.name,
4059
- intent: outcome.summary,
4060
- commitment: "high"
4061
- };
4062
- }
4063
- decisions(state) {
4064
- const decided = /* @__PURE__ */ new Map();
4065
- for (const attempt of [state.first, state.second]) for (const outcome of attempt?.outcomes ?? []) {
4066
- const report = attempt?.reports.find((candidate) => candidate.character === outcome.character) ?? this.playerReport(state, outcome);
4067
- if (report !== void 0) decided.set(outcome.character, {
4068
- outcome,
4069
- report
4070
- });
4071
- }
4072
- return decided;
4073
- }
4074
4173
  finishRound(owner, state) {
4075
4174
  const store = this.storeOf(owner);
4076
- const decided = this.decisions(state);
4175
+ const decided = decisions(state);
4077
4176
  const limit = store.settings().maxRounds;
4078
4177
  const round = state.rounds + 1;
4079
4178
  const checked = new Map([...decided.values()].flatMap(({ outcome }) => outcome.moveTo === void 0 ? [] : [[outcome.character, store.checkMove(outcome.character, outcome.moveTo)]]));
@@ -4301,6 +4400,11 @@ var TurnEngine = class {
4301
4400
  async deliver(owner, state, segments, silent, run) {
4302
4401
  const { narrationChecker } = this.boundaries();
4303
4402
  const problems = [...segments.flatMap((segment, index) => segment.type === "utterance" && segment.character === "" ? [`segment ${index + 1}: an utterance needs the character who says it`] : []), ...narrationChecker.check(segments, state.utterances)];
4403
+ const wording = wrongLanguage(this.storeOf(owner).settings().prompts.language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") });
4404
+ if (problems.length === 0 && wording !== void 0 && !silent && state.refused < MAX_REFUSALS) {
4405
+ state.refused += 1;
4406
+ throw new Error(`the output is not acceptable: ${wording}. Deliver it again with the narration corrected; utterances may not be touched`);
4407
+ }
4304
4408
  let output;
4305
4409
  if (problems.length === 0) output = {
4306
4410
  segments: asSpoken(segments, state.utterances),
@@ -4329,18 +4433,6 @@ var TurnEngine = class {
4329
4433
  return output;
4330
4434
  }
4331
4435
  };
4332
- /** The words as the character said them, whatever quotes the game master put around them. */
4333
- function asSpoken(segments, spoken) {
4334
- const left = [...spoken];
4335
- return segments.map((segment) => {
4336
- if (segment.type !== "utterance") return segment;
4337
- const at = left.findIndex((said) => said.character === segment.character && sameWords(said.text, segment.text));
4338
- return at === -1 ? segment : {
4339
- ...segment,
4340
- text: left.splice(at, 1)[0].text
4341
- };
4342
- });
4343
- }
4344
4436
  //#endregion
4345
4437
  //#region src/host/images/jobs.ts
4346
4438
  /** The same service, whose requests stand where the job's do unless a call says otherwise. */