@dsh-agentic-roleplay/core 0.1.0 → 0.2.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 (80) hide show
  1. package/README.md +1 -1
  2. package/lib/{notes-CJzbN_-E.js → activity-t7OBgHlc.js} +267 -47
  3. package/lib/authoring.js +295 -14
  4. package/lib/client.js +2599 -648
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/{documents-BBq88wXP.js → documents-Bu5uYRZB.js} +54 -33
  8. package/lib/{gallery-CjG9_4Sz.js → gallery-DUeBMHQX.js} +2 -2
  9. package/lib/{generator-pxZS-pu-.js → generator-HPifO3Kk.js} +211 -15
  10. package/lib/images.js +3 -3
  11. package/lib/index.js +849 -20
  12. package/lib/{narration-tYy6Rkfr.js → narration-BRyHU0H2.js} +28 -5
  13. package/lib/orchestration.js +803 -233
  14. package/lib/packs-ByP1J-zj.js +1334 -0
  15. package/lib/{presenter-agent-DbZALurg.js → presenter-agent-G43ODV8I.js} +3 -3
  16. package/package.json +5 -3
  17. package/prompts/en/roleplay/ask-answerer.md +3 -0
  18. package/prompts/en/roleplay/ask-question.md +2 -0
  19. package/prompts/en/roleplay/character-decide.md +1 -1
  20. package/prompts/en/roleplay/character-lookup.md +1 -1
  21. package/prompts/en/roleplay/faction-strategist.md +5 -0
  22. package/prompts/en/roleplay/game-master.md +5 -1
  23. package/prompts/en/roleplay/ooc-empty.md +1 -1
  24. package/prompts/en/roleplay/trigger-judge.md +3 -0
  25. package/prompts/en/world/procedure.md +1 -1
  26. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  27. package/prompts/zh/roleplay/ask-question.md +2 -0
  28. package/prompts/zh/roleplay/character-decide.md +1 -1
  29. package/prompts/zh/roleplay/character-lookup.md +1 -1
  30. package/prompts/zh/roleplay/faction-strategist.md +5 -0
  31. package/prompts/zh/roleplay/game-master.md +5 -1
  32. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  33. package/prompts/zh/roleplay/trigger-judge.md +3 -0
  34. package/prompts/zh/world/procedure.md +1 -1
  35. package/starter-worlds/blackwater-observatory/characters/arthur-moore/character.json +65 -0
  36. package/starter-worlds/blackwater-observatory/characters/clara-whitlock/character.json +87 -0
  37. package/starter-worlds/blackwater-observatory/characters/eleanor-graves/character.json +80 -0
  38. package/starter-worlds/blackwater-observatory/characters/marcus-reed/character.json +73 -0
  39. package/starter-worlds/blackwater-observatory/items/anonymous-letter/item.json +9 -0
  40. package/starter-worlds/blackwater-observatory/items/brass-laboratory-key/item.json +10 -0
  41. package/starter-worlds/blackwater-observatory/items/claras-gossip-notebook/item.json +9 -0
  42. package/starter-worlds/blackwater-observatory/items/harlans-notebook/item.json +10 -0
  43. package/starter-worlds/blackwater-observatory/items/investigators-coat/item.json +10 -0
  44. package/starter-worlds/blackwater-observatory/items/investigators-notebook/item.json +9 -0
  45. package/starter-worlds/blackwater-observatory/items/locked-filing-cabinet/item.json +10 -0
  46. package/starter-worlds/blackwater-observatory/items/marcus-calibration-notes/item.json +9 -0
  47. package/starter-worlds/blackwater-observatory/items/mayors-administrative-seal/item.json +9 -0
  48. package/starter-worlds/blackwater-observatory/items/municipal-lockbox/item.json +10 -0
  49. package/starter-worlds/blackwater-observatory/items/pocket-revolver/item.json +10 -0
  50. package/starter-worlds/blackwater-observatory/items/room-7-cash-receipt/item.json +9 -0
  51. package/starter-worlds/blackwater-observatory/items/rusting-mine-cart/item.json +10 -0
  52. package/starter-worlds/blackwater-observatory/items/signal-recording-strip/item.json +9 -0
  53. package/starter-worlds/blackwater-observatory/items/silver-pocket-watch/item.json +9 -0
  54. package/starter-worlds/blackwater-observatory/items/survey-archive-cabinet/item.json +10 -0
  55. package/starter-worlds/blackwater-observatory/items/surveyors-map/item.json +10 -0
  56. package/starter-worlds/blackwater-observatory/items/unknown-visitors-note-fragment/item.json +10 -0
  57. package/starter-worlds/blackwater-observatory/locations/blackwater-ridge/location.json +5 -0
  58. package/starter-worlds/blackwater-observatory/locations/iron-stag-bar/location.json +30 -0
  59. package/starter-worlds/blackwater-observatory/locations/iron-stag-room-7/location.json +18 -0
  60. package/starter-worlds/blackwater-observatory/locations/north-forest-cabin/location.json +18 -0
  61. package/starter-worlds/blackwater-observatory/locations/observatory-directors-office/location.json +20 -0
  62. package/starter-worlds/blackwater-observatory/locations/observatory-telescope-chamber/location.json +25 -0
  63. package/starter-worlds/blackwater-observatory/locations/old-mine-entrance/location.json +27 -0
  64. package/starter-worlds/blackwater-observatory/locations/old-mine-main-tunnel/location.json +13 -0
  65. package/starter-worlds/blackwater-observatory/locations/town-hall-mayors-office/location.json +25 -0
  66. package/starter-worlds/blackwater-observatory/locations/town-hall-records-room/location.json +13 -0
  67. package/starter-worlds/blackwater-observatory/locations/town-square/location.json +30 -0
  68. package/starter-worlds/blackwater-observatory/triggers.json +20 -0
  69. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  70. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  71. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  72. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  73. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  74. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  75. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  76. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  77. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  78. package/starter-worlds/blackwater-observatory/variables.json +39 -0
  79. package/starter-worlds/blackwater-observatory/world.json +27 -0
  80. package/lib/worlds-Bj-EGS_i.js +0 -478
@@ -1,18 +1,19 @@
1
1
  import { n as roleplaySessionOf, t as chatSessionId } from "./chat-AKrVcWIC.js";
2
- import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-tYy6Rkfr.js";
3
- import { i as parsePlotsFile, t as API_PREFIX, y as shippedText } from "./worlds-Bj-EGS_i.js";
4
- import { C as slug, D as runChild, T as childSampling, a as addToLibrary, w as uniqueKey } from "./generator-pxZS-pu-.js";
5
- import { C as readTime, S as endRound, T as zoneOf, _ as sameWords, a as readNotes, b as describeTime, c as describePacingAdvice, h as Timelines, i as putNote, l as pacingAdvice, n as clearNotes, p as updatePlotProgress, s as addSessionPlot, t as addToNote, u as plotAuthorNeeded, v as ClockError, w as skipTime, x as describeWhen, y as beginTurn } from "./notes-CJzbN_-E.js";
6
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CjG9_4Sz.js";
2
+ import { F as shippedText, U as INTENT_STATUSES, _ as API_PREFIX, b as parsePlotsFile } from "./packs-ByP1J-zj.js";
3
+ import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-BRyHU0H2.js";
4
+ import "./src-CWTNeL6Y.js";
5
+ import { A as runChild, D as childSampling, E as childModel, T as uniqueKey, j as estimateAnswer, k as childTrace, o as addToLibrary, w as slug } from "./generator-HPifO3Kk.js";
6
+ import { A as readTime, D as describeTime, E as beginTurn, F as CHARACTER_ACTION_SCHEMA, I as RESULTS, L as answerEstimate, M as zoneOf, N as referent, O as describeWhen, P as AWAY_ACTION_SCHEMA, R as parseCharacterAction, T as ClockError, _ as putNote, a as recordActivity, b as Timelines, c as describePacingAdvice, h as clearNotes, j as skipTime, k as endRound, l as pacingAdvice, m as addToNote, n as keepRunDetail, p as updatePlotProgress, s as addSessionPlot, t as forgetRunDetails, u as plotAuthorNeeded, v as readNotes, w as sameWords } from "./activity-t7OBgHlc.js";
7
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DUeBMHQX.js";
7
8
  import { t as promptFor } from "./access-C1nFQiyT.js";
8
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-DbZALurg.js";
9
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-G43ODV8I.js";
9
10
  import { join } from "node:path";
10
11
  import { existsSync } from "node:fs";
11
12
  import { SessionId } from "@deepseek-ai/dsh-session";
12
13
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
13
14
  import { defineTool } from "@deepseek-ai/dsh-tools";
14
15
  import { readdir } from "node:fs/promises";
15
- import { ENGAGEMENT_GRACE, ITEM_ACTIONS, InvalidEditError, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, characterKey, createCharacterTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, inAudience, itemKey, lintWorld, localTime, locationKey, mentioned, nextOccurrence, occurrenceAt, parseInstant, parseRecordsEdit, planItemChange, planVariableChange, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
16
+ import { ENGAGEMENT_GRACE, ITEM_ACTIONS, InvalidEditError, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, characterKey, createCharacterTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, inAudience, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, nextOccurrence, occurrenceAt, parseInstant, parseRecordsEdit, planItemChange, planVariableChange, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
16
17
  //#region src/host/orchestration/committer.ts
17
18
  /** What the keeper reads back by default: the parts of the records its edits write. */
18
19
  const VERIFY_SECTIONS = [
@@ -28,7 +29,7 @@ const VERIFY_SECTIONS = [
28
29
  "engagements"
29
30
  ];
30
31
  const label = (round) => `turn ${round.turn}, round ${round.round}`;
31
- function describeRound(round) {
32
+ function describeRound(round, known) {
32
33
  return [
33
34
  `## ${label(round)}`,
34
35
  round.offstage === true ? `Off stage (away from the player's character; only the characters named here perceive it, and only those who were together perceive each other): ${round.situation}` : `The moment (includes what the player's character did or said): ${round.situation}`,
@@ -36,7 +37,7 @@ function describeRound(round) {
36
37
  ...round.time === void 0 ? [] : [`When: ${describeInstant(round.time.from, round.time.zone)} (${dayPart(localTime(round.time.from, round.time.zone).minuteOfDay)})${round.time.to > round.time.from ? `; the round took ${describeDuration(round.time.to - round.time.from)}` : ""}`],
37
38
  "What each character did, and what became of it:",
38
39
  ...round.entries.map((entry) => [
39
- entry.forced === true ? `- ${entry.character} (${entry.name}): decreed, not chosen: ${entry.result}: ${entry.summary}` : entry.player === true ? `- ${entry.character} (${entry.name}, the player's character): ${entry.result}: ${entry.summary}` : `- ${entry.character} (${entry.name}): intended "${entry.intent}" [commitment: ${entry.commitment}]; ${entry.result}: ${entry.summary}`,
40
+ entry.forced === true ? `- ${entry.character} (${known.get(entry.character) ?? entry.name}): decreed, not chosen: ${entry.result}: ${entry.summary}` : entry.player === true ? `- ${entry.character} (${known.get(entry.character) ?? entry.name}, the player's character): ${entry.result}: ${entry.summary}` : `- ${entry.character} (${known.get(entry.character) ?? entry.name}): intended "${entry.intent}" [commitment: ${entry.commitment}]; ${entry.result}: ${entry.summary}`,
40
41
  entry.utterance === void 0 ? "" : ` said${entry.spoken ? "" : " (but was prevented from saying)"}: "${entry.utterance}"`,
41
42
  entry.publicState === void 0 ? "" : ` the game master says anyone present can now see: ${entry.publicState}`,
42
43
  entry.variables === void 0 ? "" : ` the game master changed what is tracked: ${entry.variables.map((change) => `${change.subject}'s ${change.name} ${change.from} -> ${change.to}`).join("; ")}`,
@@ -55,6 +56,7 @@ function describePrompt(job, memory) {
55
56
  const first = job.rounds[0];
56
57
  const records = job.store.story.records({ timeZone: zoneOf(job.store.settings().clock) });
57
58
  const own = job.store.story.records({ rounds }).events;
59
+ const known = new Map(job.store.cast().map((member) => [member.key, referent(member.character)]));
58
60
  const before = records.events.filter((event) => event.turn < first.turn || event.turn === first.turn && event.round < first.round).slice(-6);
59
61
  return [
60
62
  memory.flaky ? "Perception in this chat: characters do not perceive perfectly. Mark a perception partial only when the character could take in just part of it (overheard, glimpsed), and mistaken only when the material shows it taking in something false; in both cases put the character's own version in content. Otherwise it is accurate and content is left out." : "Perception in this chat: every character perceives exactly what happened. Leave accuracy and content out.",
@@ -63,9 +65,9 @@ function describePrompt(job, memory) {
63
65
  job.rounds.length > 1 ? `${job.rounds.length} rounds are due for records: write all of them, oldest first.` : `${label(first)} is due for records.`,
64
66
  ...job.focus === void 0 || job.focus.length === 0 ? [] : ["", `The game master says this is worth keeping: ${job.focus.join("; ")}`],
65
67
  "",
66
- ...job.rounds.flatMap(describeRound),
68
+ ...job.rounds.flatMap((round) => describeRound(round, known)),
67
69
  "## State of the characters now",
68
- ...records.characters.map((entry) => `- ${entry.character} (${entry.name}, ${entry.controlled_by}): public: ${entry.public_state || "-"}; inner: ${entry.inner_state || "-"}; doing: ${entry.activity || "-"}${entry.location === null ? "" : `; in: ${entry.location}${entry.position === "" ? "" : ` (${entry.position})`}`}`),
70
+ ...records.characters.map((entry) => `- ${entry.character} (${known.get(entry.character) ?? entry.name}, ${entry.controlled_by}): public: ${entry.public_state || "-"}; inner: ${entry.inner_state || "-"}; doing: ${entry.activity || "-"}${entry.location === null ? "" : `; in: ${entry.location}${entry.position === "" ? "" : ` (${entry.position})`}`}`),
69
71
  "",
70
72
  "## Recorded before these rounds (do not repeat)",
71
73
  ...before.length === 0 ? ["- nothing"] : before.map((event) => `- [turn ${event.turn}] ${event.text}`),
@@ -86,7 +88,7 @@ function describePrompt(job, memory) {
86
88
  ...records.open_threads.length === 0 ? ["- none"] : records.open_threads.map((thread) => `- id ${thread.id}: ${thread.text}`)
87
89
  ].join("\n");
88
90
  }
89
- const RESULT$2 = {
91
+ const RESULT$4 = {
90
92
  type: "object",
91
93
  properties: {
92
94
  complete: {
@@ -186,10 +188,12 @@ function recordKeeper(deps) {
186
188
  signal,
187
189
  reasoningEffort: job.store.settings().reasoning.children,
188
190
  sampling: childSampling(job.store.settings(), "records"),
191
+ ...childModel(job.store.settings(), "records"),
192
+ trace: childTrace(job.store, "records", "record keeper"),
189
193
  persona: promptFor(parent, "roleplay/record-keeper", job.store.settings().prompts.language),
190
194
  prompt: describePrompt(job, memory),
191
195
  tools: keeperTools(job, memory, progress),
192
- result: RESULT$2,
196
+ result: RESULT$4,
193
197
  beforeSubmit: () => {
194
198
  if (progress.edits === 0 && !warned) {
195
199
  warned = true;
@@ -218,7 +222,7 @@ function suggestionProblems(lines, wanted) {
218
222
  const tidySuggestions = (lines) => lines.map((line) => line.trim().replace(/\s+/g, " "));
219
223
  //#endregion
220
224
  //#region src/host/orchestration/suggester.ts
221
- const RESULT$1 = {
225
+ const RESULT$3 = {
222
226
  type: "object",
223
227
  properties: { options: {
224
228
  type: "array",
@@ -237,7 +241,7 @@ function promptOf(job) {
237
241
  const place = player?.place?.location.name;
238
242
  return [
239
243
  `Write exactly ${job.count} suggestion${job.count === 1 ? "" : "s"}.`,
240
- `The player plays ${player?.character.name ?? "their character"}${place === void 0 ? "" : `, who is at ${place}`}.`,
244
+ `The player plays ${player === void 0 ? "their character" : referent(player.character)}${place === void 0 ? "" : `, who is at ${place}`}.`,
241
245
  "",
242
246
  "What the player has just read:",
243
247
  readingOf(job)
@@ -252,10 +256,12 @@ function suggestionWriter(deps) {
252
256
  parent,
253
257
  signal,
254
258
  reasoningEffort: job.store.settings().reasoning.children,
255
- sampling: childSampling(job.store.settings(), "suggestions"),
259
+ sampling: childSampling(job.store.settings(), "suggestions", estimateAnswer(Array.from({ length: job.count }, () => 200), job.store.settings().prompts.language)),
260
+ ...childModel(job.store.settings(), "suggestions"),
261
+ trace: childTrace(job.store, "suggestions", "suggestions"),
256
262
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
257
263
  prompt: promptOf(job),
258
- result: RESULT$1,
264
+ result: RESULT$3,
259
265
  beforeSubmit: (value) => {
260
266
  const problems = suggestionProblems(tidySuggestions(value.options), job.count);
261
267
  return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
@@ -265,6 +271,317 @@ function suggestionWriter(deps) {
265
271
  } };
266
272
  }
267
273
  //#endregion
274
+ //#region src/host/triggers/judged.ts
275
+ const KEY = "triggers.judged";
276
+ function readVerdicts(session) {
277
+ const stored = session.metadata.getValue(KEY);
278
+ if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
279
+ const verdicts = {};
280
+ for (const [statement, value] of Object.entries(stored)) {
281
+ const verdict = value;
282
+ if (typeof verdict === "object" && verdict !== null && typeof verdict.holds === "boolean" && typeof verdict.turn === "number") verdicts[statement] = {
283
+ holds: verdict.holds,
284
+ turn: verdict.turn
285
+ };
286
+ }
287
+ return verdicts;
288
+ }
289
+ /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
290
+ function writeVerdicts(session, verdicts, keep) {
291
+ session.metadata.setValue(KEY, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
292
+ }
293
+ /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
294
+ const verdictReader = (session) => {
295
+ const verdicts = readVerdicts(session);
296
+ return (statement) => verdicts[statement]?.holds === true;
297
+ };
298
+ //#endregion
299
+ //#region src/host/triggers/judge.ts
300
+ const RESULT$2 = {
301
+ type: "object",
302
+ properties: { verdicts: {
303
+ type: "array",
304
+ items: {
305
+ type: "object",
306
+ properties: {
307
+ number: {
308
+ type: "integer",
309
+ description: "The number of the statement, as listed."
310
+ },
311
+ holds: { type: "boolean" },
312
+ reason: {
313
+ type: "string",
314
+ description: "A short reason that points at what you were shown."
315
+ }
316
+ },
317
+ required: [
318
+ "number",
319
+ "holds",
320
+ "reason"
321
+ ],
322
+ additionalProperties: false
323
+ },
324
+ description: "One verdict for each statement."
325
+ } },
326
+ required: ["verdicts"],
327
+ additionalProperties: false
328
+ };
329
+ /** The statements of the triggers still waiting, each once. */
330
+ function waitingStatements(job) {
331
+ return [...new Set(job.store.story.triggers.list({ status: "dormant" }).flatMap((trigger) => judgedStatements(trigger.condition)))];
332
+ }
333
+ function brief$1(job, statements) {
334
+ const events = job.store.story.events.list().slice(-15).map((event) => `- ${event.text}`);
335
+ const cast = job.store.cast().map((member) => `- ${member.character.name}${member.place === void 0 ? "" : ` (at ${member.place.location.name})`}${member.state === void 0 ? "" : `: ${[member.state.publicState, member.state.activity].filter((text) => text !== "").join("; ")}`}`);
336
+ return [
337
+ "Statements to judge:",
338
+ ...statements.map((statement, index) => `${index + 1}. ${statement}`),
339
+ `Recorded events, the latest last:\n${events.join("\n") || "- none yet"}`,
340
+ `Where everyone is and what they are doing:\n${cast.join("\n") || "- nobody"}`
341
+ ].join("\n\n");
342
+ }
343
+ /**
344
+ * After a turn, has a model say whether the statements that triggers wait on hold now, for no more than `triggers.judgedPerTurn` of them, the
345
+ * longest unjudged first, in one request. The verdicts are stored; a trigger fires from them at the next look, like from any other condition.
346
+ */
347
+ function triggerJudge(deps) {
348
+ return { async judge(job, signal) {
349
+ const { judgedPerTurn } = job.store.settings().triggers;
350
+ const waiting = waitingStatements(job);
351
+ const verdicts = readVerdicts(job.store.story);
352
+ writeVerdicts(job.store.story, verdicts, new Set(waiting));
353
+ if (judgedPerTurn === 0 || waiting.length === 0) return { judged: 0 };
354
+ const statements = [...waiting].sort((a, b) => (verdicts[a]?.turn ?? -1) - (verdicts[b]?.turn ?? -1)).slice(0, judgedPerTurn);
355
+ const parent = deps.agentOf(job.chat);
356
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
357
+ const store = job.store;
358
+ const answer = await runChild({
359
+ parent,
360
+ signal,
361
+ reasoningEffort: store.settings().reasoning.children,
362
+ sampling: childSampling(store.settings(), "records"),
363
+ ...childModel(store.settings(), "records"),
364
+ trace: childTrace(store, "records", "trigger judge"),
365
+ persona: promptFor(parent, "roleplay/trigger-judge", store.settings().prompts.language),
366
+ prompt: brief$1(job, statements),
367
+ result: RESULT$2,
368
+ beforeSubmit: (value) => {
369
+ const numbers = value.verdicts.map((verdict) => verdict.number);
370
+ const missing = statements.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
371
+ return missing.length === 0 ? void 0 : `judge every statement: ${missing.join(", ")} ${missing.length === 1 ? "has" : "have"} no verdict`;
372
+ },
373
+ maxCalls: 3
374
+ });
375
+ const next = readVerdicts(store.story);
376
+ for (const verdict of answer.verdicts) {
377
+ const statement = statements[verdict.number - 1];
378
+ if (statement !== void 0) next[statement] = {
379
+ holds: verdict.holds,
380
+ turn: job.turn
381
+ };
382
+ }
383
+ writeVerdicts(store.story, next, new Set(waiting));
384
+ return { judged: answer.verdicts.length };
385
+ } };
386
+ }
387
+ //#endregion
388
+ //#region src/host/factions/strategist.ts
389
+ const LAST_KEY = "strategy.last";
390
+ const DAY_MS = 864e5;
391
+ /** Rounds numbered from here belong to what organisations did, as off-stage rounds have their own range. */
392
+ const STRATEGY_ROUND = 200;
393
+ const MAX_ACTIVE_GOALS = 8;
394
+ const MAX_TEXT = 400;
395
+ const keyOf$1 = (faction) => faction.sourceId ?? String(faction.id);
396
+ function lastActed(session) {
397
+ const stored = session.metadata.getValue(LAST_KEY);
398
+ return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
399
+ }
400
+ /**
401
+ * The organisations whose time has come: they have a goal in hand, and `everyDays` of story time have passed since they last decided.
402
+ * One seen for the first time starts its clock now and is not due yet. Longest waiting first.
403
+ */
404
+ function dueFactions(session, now, everyDays) {
405
+ const last = lastActed(session);
406
+ const due = [];
407
+ for (const faction of session.factions.list()) {
408
+ const key = keyOf$1(faction);
409
+ if (last[key] === void 0) {
410
+ last[key] = now;
411
+ continue;
412
+ }
413
+ if (now - last[key] < everyDays * DAY_MS) continue;
414
+ if (session.factionIntents.list(faction.id, { status: "active" }).length === 0) continue;
415
+ due.push({
416
+ faction,
417
+ since: last[key]
418
+ });
419
+ }
420
+ session.metadata.setValue(LAST_KEY, last);
421
+ return due.sort((a, b) => a.since - b.since).map((entry) => entry.faction);
422
+ }
423
+ function markActed(session, faction, now) {
424
+ session.metadata.setValue(LAST_KEY, {
425
+ ...lastActed(session),
426
+ [keyOf$1(faction)]: now
427
+ });
428
+ }
429
+ const RESULT$1 = {
430
+ type: "object",
431
+ properties: {
432
+ summary: {
433
+ type: "string",
434
+ description: "One concrete thing the organisation does in this time, in the past tense, in one or two sentences; or that it waits, and why."
435
+ },
436
+ public_state: {
437
+ type: "string",
438
+ description: "Its public state afterwards, only when outsiders could see it change."
439
+ },
440
+ inner_state: {
441
+ type: "string",
442
+ description: "Its private state afterwards, only when its inner position moved."
443
+ },
444
+ goal_updates: {
445
+ type: "array",
446
+ items: {
447
+ type: "object",
448
+ properties: {
449
+ id: {
450
+ type: "integer",
451
+ description: "The number of the goal, as listed."
452
+ },
453
+ status: {
454
+ type: "string",
455
+ enum: [...INTENT_STATUSES]
456
+ }
457
+ },
458
+ required: ["id", "status"],
459
+ additionalProperties: false
460
+ },
461
+ description: "Goals whose status changed."
462
+ },
463
+ new_goal: {
464
+ type: "object",
465
+ properties: {
466
+ name: { type: "string" },
467
+ description: { type: "string" },
468
+ plan: {
469
+ type: "array",
470
+ items: { type: "string" }
471
+ }
472
+ },
473
+ required: [
474
+ "name",
475
+ "description",
476
+ "plan"
477
+ ],
478
+ additionalProperties: false,
479
+ description: "At most one new goal, when the situation calls for it."
480
+ }
481
+ },
482
+ required: ["summary"],
483
+ additionalProperties: false
484
+ };
485
+ function brief(session, faction, now, zone, since) {
486
+ const state = session.factionStates.get(faction.id);
487
+ const named = (id) => session.characters.get(id)?.name ?? String(id);
488
+ const goals = session.factionIntents.list(faction.id, { status: "active" });
489
+ const members = session.factionMemberships.ofFaction(faction.id, "active").map((member) => `${named(member.characterId)} (${[member.role, member.rank].filter((part) => part !== "").join(", ") || "member"})`);
490
+ const standing = session.factionRelationships.from("faction", faction.id).map((relation) => {
491
+ return `${(relation.toKind === "faction" ? session.factions.get(relation.toId)?.name : named(relation.toId)) ?? relation.toId}: ${relation.label}${relation.summary === "" ? "" : ` - ${relation.summary}`}`;
492
+ });
493
+ const events = session.events.list().slice(-8).map((event) => `- ${event.text}`);
494
+ return [
495
+ `Organisation: ${faction.name}${faction.summary === "" ? "" : ` - ${faction.summary}`}`,
496
+ faction.description === "" ? "" : `About it: ${faction.description}`,
497
+ faction.values.length === 0 ? "" : `Values: ${faction.values.join("; ")}`,
498
+ faction.structure === "" ? "" : `Structure: ${faction.structure}`,
499
+ `Public state: ${state?.publicState || "(nothing stated)"}`,
500
+ `Private state: ${state?.innerState || "(nothing stated)"}`,
501
+ "Goals in hand:",
502
+ ...goals.map((goal) => `- ${goal.id}. ${goal.name} (${goal.type}): ${goal.description}${goal.plan.length === 0 ? "" : ` Next: ${goal.plan.join("; ")}.`}${goal.deadline === void 0 ? "" : ` By ${goal.deadline}.`}`),
503
+ members.length === 0 ? "" : `Members: ${members.join("; ")}`,
504
+ standing.length === 0 ? "" : `Its standing with others:\n${standing.map((line) => `- ${line}`).join("\n")}`,
505
+ `It is ${describeWhen(now, now, zone)} now; the organisation last decided ${describeDuration(now - since)} ago.`,
506
+ events.length === 0 ? "" : `What has happened lately:\n${events.join("\n")}`,
507
+ "Decide what the organisation does."
508
+ ].filter((line) => line !== "").join("\n");
509
+ }
510
+ function applyStrategy(job, session, faction, strategy, now) {
511
+ const active = session.factionIntents.list(faction.id, { status: "active" });
512
+ session.transaction(() => {
513
+ if (strategy.public_state !== void 0 || strategy.inner_state !== void 0) session.factionStates.update(faction.id, {
514
+ ...strategy.public_state === void 0 ? {} : { publicState: strategy.public_state.slice(0, MAX_TEXT) },
515
+ ...strategy.inner_state === void 0 ? {} : { innerState: strategy.inner_state.slice(0, MAX_TEXT) }
516
+ });
517
+ for (const update of strategy.goal_updates ?? []) if (active.some((goal) => goal.id === update.id)) session.factionIntents.update(update.id, { status: update.status });
518
+ const goal = strategy.new_goal;
519
+ const room = MAX_ACTIVE_GOALS - session.factionIntents.list(faction.id, { status: "active" }).length;
520
+ if (goal !== void 0 && goal.name.trim() !== "" && room > 0) session.factionIntents.add(faction.id, {
521
+ type: "agenda",
522
+ name: goal.name.trim().slice(0, 120),
523
+ description: goal.description.slice(0, MAX_TEXT),
524
+ status: "active",
525
+ horizon: "short",
526
+ priority: .5,
527
+ urgency: .4,
528
+ plan: goal.plan.slice(0, 6).map((step) => step.slice(0, 200)),
529
+ openThreads: [],
530
+ constraints: []
531
+ });
532
+ session.edit({
533
+ turn: job.turn,
534
+ events: [{
535
+ turn: job.turn,
536
+ round: STRATEGY_ROUND,
537
+ text: `${faction.name}: ${strategy.summary.slice(0, MAX_TEXT)}`,
538
+ importance: 3,
539
+ tags: ["faction", faction.name],
540
+ involves: [],
541
+ perceivedBy: []
542
+ }]
543
+ }, { seal: true });
544
+ });
545
+ markActed(session, faction, now);
546
+ }
547
+ /**
548
+ * Has organisations decide, one request each and one after another, what they do as story time passes. They are bounded by the chat
549
+ * (`factions.perTurn`, one decision per `factions.everyDays` of story time each), and a failure leaves the organisation as it was.
550
+ */
551
+ function factionStrategist(deps) {
552
+ return { async strategize(job, signal) {
553
+ const { perTurn, everyDays } = job.store.settings().factions;
554
+ const acted = [];
555
+ if (perTurn === 0) return { acted };
556
+ const parent = deps.agentOf(job.chat);
557
+ if (parent === void 0) throw new Error(`no agent for chat ${job.chat}`);
558
+ const session = job.store.story;
559
+ const { now, zone } = job.store.time(job.turn);
560
+ const last = lastActed(session);
561
+ for (const faction of dueFactions(session, now, everyDays).slice(0, perTurn)) {
562
+ const store = job.store;
563
+ const strategy = await runChild({
564
+ parent,
565
+ signal,
566
+ reasoningEffort: store.settings().reasoning.children,
567
+ sampling: childSampling(store.settings(), "authoring"),
568
+ ...childModel(store.settings(), "authoring"),
569
+ trace: childTrace(store, "authoring", `faction ${faction.name}`),
570
+ persona: promptFor(parent, "roleplay/faction-strategist", store.settings().prompts.language),
571
+ prompt: brief(session, faction, now, zone, last[keyOf$1(faction)] ?? now),
572
+ result: RESULT$1,
573
+ maxCalls: 3
574
+ });
575
+ applyStrategy(job, session, faction, strategy, now);
576
+ acted.push({
577
+ faction: faction.name,
578
+ summary: strategy.summary
579
+ });
580
+ }
581
+ return { acted };
582
+ } };
583
+ }
584
+ //#endregion
268
585
  //#region src/host/authoring/author-agent.ts
269
586
  function authorTools(job, work, mode, limits) {
270
587
  const link = {
@@ -510,6 +827,8 @@ function worldAuthor(deps) {
510
827
  const result = await runChild({
511
828
  reasoningEffort: job.store.settings().reasoning.children,
512
829
  sampling: childSampling(job.store.settings(), "authoring"),
830
+ ...childModel(job.store.settings(), "authoring"),
831
+ trace: childTrace(job.store, "authoring", "world author"),
513
832
  parent,
514
833
  signal,
515
834
  persona: promptFor(parent, "world/author", job.store.settings().prompts.language),
@@ -547,14 +866,17 @@ function worldAuthor(deps) {
547
866
  };
548
867
  const parent = parentOf(job.chat);
549
868
  const { authoring } = job.store.settings();
869
+ const work = { created: [] };
550
870
  const result = await runChild({
551
871
  reasoningEffort: job.store.settings().reasoning.children,
552
872
  sampling: childSampling(job.store.settings(), "authoring"),
873
+ ...childModel(job.store.settings(), "authoring"),
874
+ trace: childTrace(job.store, "authoring", "world consolidation"),
553
875
  parent,
554
876
  signal,
555
877
  persona: promptFor(parent, "world/consolidate", job.store.settings().prompts.language),
556
878
  prompt: consolidationPrompt(job),
557
- tools: authorTools(job, { created: [] }, "consolidate", authoring),
879
+ tools: authorTools(job, work, "consolidate", authoring),
558
880
  result: CONSOLIDATE_RESULT,
559
881
  beforeSubmit: (value) => {
560
882
  if (!value.complete) return void 0;
@@ -585,7 +907,8 @@ function fireTriggers(session, input) {
585
907
  round,
586
908
  now,
587
909
  zone,
588
- maxFires: settings.triggers.maxFires
910
+ maxFires: settings.triggers.maxFires,
911
+ judged: verdictReader(session)
589
912
  });
590
913
  for (const failure of run.failed) problem(`the trigger "${failure.trigger.key}" could not fire and is given up: ${failure.problem}`);
591
914
  const names = new Map(session.characters.list().map((character) => [character.id, character.name]));
@@ -680,6 +1003,35 @@ function noteStore(session, settings, clock) {
680
1003
  };
681
1004
  }
682
1005
  //#endregion
1006
+ //#region src/host/orchestration/observation.ts
1007
+ /** What a character takes in where it stands and of what it carries: the place, the ways out and what they lead to, what lies in the open, what it holds. */
1008
+ function observeSurroundings(session, characterId, turn) {
1009
+ const placement = session.placements.get("character", characterId);
1010
+ if (placement !== void 0) {
1011
+ session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1012
+ for (const exit of session.locations.exitsFrom(placement.locationId)) {
1013
+ session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1014
+ session.knowledge.learn(characterId, "location", exit.toId, turn);
1015
+ }
1016
+ for (const { item } of session.items.contents({
1017
+ kind: "location",
1018
+ id: placement.locationId
1019
+ })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1020
+ }
1021
+ for (const { item } of session.items.contents({
1022
+ kind: "character",
1023
+ id: characterId
1024
+ })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1025
+ }
1026
+ /**
1027
+ * The player's character is never asked to act, so nothing else shows it its surroundings: it takes them in when a turn begins, which is
1028
+ * how it comes to know the way back from where it went.
1029
+ */
1030
+ function observeAsPlayer(session, turn) {
1031
+ const player = session.characters.list().find((character) => character.control === "player");
1032
+ if (player !== void 0) observeSurroundings(session, player.id, turn);
1033
+ }
1034
+ //#endregion
683
1035
  //#region src/host/clock/agenda.ts
684
1036
  const CURSOR = "agenda.cursor";
685
1037
  const ASKED = "agenda.asked";
@@ -1018,30 +1370,16 @@ function carriedBy(session, characterId) {
1018
1370
  });
1019
1371
  }
1020
1372
  function knowledgeOf(session, characterId, turn, visibleCharacters) {
1373
+ observeSurroundings(session, characterId, turn);
1021
1374
  const placement = session.placements.get("character", characterId);
1022
- if (placement !== void 0) {
1023
- session.knowledge.learn(characterId, "location", placement.locationId, turn, true);
1024
- for (const exit of session.locations.exitsFrom(placement.locationId)) {
1025
- session.knowledge.learn(characterId, "exit", exit.id, turn, true);
1026
- session.knowledge.learn(characterId, "location", exit.toId, turn);
1027
- }
1028
- for (const { item } of session.items.contents({
1029
- kind: "location",
1030
- id: placement.locationId
1031
- })) if (!item.hidden) session.knowledge.learn(characterId, "item", item.id, turn, true);
1032
- }
1033
1375
  for (const otherId of visibleCharacters ?? (placement === void 0 ? [] : session.placements.at(placement.locationId, "character").map((other) => other.entityId))) if (otherId !== characterId && session.relationships.get(characterId, otherId) === void 0) session.relationships.upsert(characterId, otherId, { label: "acquaintance" }, turn);
1034
- for (const { item } of session.items.contents({
1035
- kind: "character",
1036
- id: characterId
1037
- })) session.knowledge.learn(characterId, "item", item.id, turn, true);
1038
1376
  const locations = session.knowledge.list(characterId, "location").flatMap((entry) => {
1039
1377
  const place = session.locations.get(entry.subjectId);
1040
- return place === void 0 ? [] : [`${place.name} (${locationKey(place)})`];
1378
+ return place === void 0 ? [] : [place.name];
1041
1379
  });
1042
1380
  const items = session.knowledge.list(characterId, "item").flatMap((entry) => {
1043
1381
  const item = session.items.get(entry.subjectId);
1044
- return item === void 0 ? [] : [`${item.name} (${itemKey(item)})`];
1382
+ return item === void 0 ? [] : [item.name];
1045
1383
  });
1046
1384
  const allExits = session.locations.allExits();
1047
1385
  const routes = session.knowledge.list(characterId, "exit").flatMap((entry) => {
@@ -1053,11 +1391,11 @@ function knowledgeOf(session, characterId, turn, visibleCharacters) {
1053
1391
  return {
1054
1392
  characters: session.relationships.from(characterId).flatMap((relation) => {
1055
1393
  const character = session.characters.get(relation.toId);
1056
- return character === void 0 ? [] : [`${character.name} (${keyOfCharacter(character)})`];
1394
+ return character === void 0 ? [] : [character.name];
1057
1395
  }),
1058
1396
  factions: session.factionRelationships.from("character", characterId).filter((relation) => relation.toKind === "faction").flatMap((relation) => {
1059
1397
  const faction = session.factions.get(relation.toId);
1060
- return faction === void 0 ? [] : [`${faction.name} (${faction.sourceId ?? faction.id})`];
1398
+ return faction === void 0 ? [] : [faction.name];
1061
1399
  }),
1062
1400
  locations,
1063
1401
  items,
@@ -1233,7 +1571,10 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
1233
1571
  text: (id, variables) => prompt(settings().prompts.language, id, variables),
1234
1572
  rules: () => rulesOf(worldRules(session), settings().rules.own),
1235
1573
  time: (turn) => readTime(session, settings().clock, turn, wall()),
1236
- beginTurn: (turn) => startTurn(session, settings().clock, turn, wall()),
1574
+ beginTurn: (turn) => {
1575
+ observeAsPlayer(session, turn);
1576
+ return startTurn(session, settings().clock, turn, wall());
1577
+ },
1237
1578
  endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum),
1238
1579
  skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request),
1239
1580
  checkVariableChanges: (changes) => changes.flatMap((spec) => {
@@ -1272,6 +1613,10 @@ function storeOf(session, folder, problem, queryVector, wall, prompt) {
1272
1613
  addNote: (kind, turn, lines) => {
1273
1614
  addToNote(session, kind, turn, lines);
1274
1615
  },
1616
+ recordActivity: (entry, detail) => {
1617
+ if (detail !== void 0 && entry.run !== void 0) keepRunDetail(folder, entry.run, detail);
1618
+ forgetRunDetails(folder, recordActivity(session, entry));
1619
+ },
1275
1620
  notes: () => readNotes(session),
1276
1621
  clearNotes: () => {
1277
1622
  clearNotes(session);
@@ -1318,13 +1663,18 @@ function storesOf(state, sessionsDir, problem = () => void 0, queryVector = () =
1318
1663
  }
1319
1664
  //#endregion
1320
1665
  //#region src/shared/ooc.ts
1321
- /** What the player writes to give the game master an out-of-character command: a turn of its own, never mixed with an action of the character. */
1322
- const OOC_COMMAND = /^\s*\/ooc(?=\s|$)\s*([\s\S]*)$/i;
1323
- /** The command in a player's message, or nothing when the message is an ordinary action. The command may be empty. */
1666
+ /** What the player writes to speak to the game master as the author of the story: a command (`/ooc`) or a question (`/ask`), a turn of its own, never mixed with an action of the character. */
1667
+ const OOC_COMMAND = /^\s*\/(ooc|ask)(?=\s|$)\s*([\s\S]*)$/i;
1668
+ /** The command or question in a player's message, or nothing when the message is an ordinary action. The request may be empty. */
1324
1669
  function parseOoc(text) {
1325
1670
  const match = OOC_COMMAND.exec(text);
1326
- return match === null ? void 0 : { request: (match[1] ?? "").trim() };
1671
+ return match === null ? void 0 : {
1672
+ request: (match[2] ?? "").trim(),
1673
+ question: match[1].toLowerCase() === "ask"
1674
+ };
1327
1675
  }
1676
+ /** The longest answer to an out-of-character question. */
1677
+ const MAX_OOC_ANSWER = 1200;
1328
1678
  //#endregion
1329
1679
  //#region src/host/orchestration/hooks.ts
1330
1680
  const notice = (text) => createUserMessage({
@@ -1342,6 +1692,25 @@ function ownerOf(agent, turn) {
1342
1692
  turn
1343
1693
  };
1344
1694
  }
1695
+ /** Where the withdrawal of an agent's preview tool is kept: on the agent, so that a reloaded plugin still finds what its earlier self registered. */
1696
+ const PREVIEW_SHOWN = Symbol.for("dsh-agentic-roleplay.preview-tool");
1697
+ /** Registers the preview tool on the agent of a chat that shows one, once, and withdraws it when the setting is turned off. */
1698
+ function previewToggle(tool) {
1699
+ return (agent, enabled) => {
1700
+ const holder = agent;
1701
+ const withdraw = holder[PREVIEW_SHOWN];
1702
+ if (enabled && withdraw === void 0) try {
1703
+ holder[PREVIEW_SHOWN] = agent.ctx.tools.register(tool);
1704
+ } catch (error) {
1705
+ if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
1706
+ holder[PREVIEW_SHOWN] = () => void 0;
1707
+ }
1708
+ else if (!enabled && withdraw !== void 0) {
1709
+ delete holder[PREVIEW_SHOWN];
1710
+ withdraw();
1711
+ }
1712
+ };
1713
+ }
1345
1714
  /**
1346
1715
  * The listeners of a roleplay preset. Preset listeners are shared by every chat
1347
1716
  * that uses the preset and also hear the agents that chat spawns, so each one
@@ -1349,15 +1718,7 @@ function ownerOf(agent, turn) {
1349
1718
  */
1350
1719
  function installHooks(ctx, deps) {
1351
1720
  const { engine, boundaries, stores, timelines, previewTool } = deps;
1352
- const shown = /* @__PURE__ */ new WeakMap();
1353
- const showPreviewTool = (agent, enabled) => {
1354
- const withdraw = shown.get(agent);
1355
- if (enabled && withdraw === void 0) shown.set(agent, agent.ctx.tools.register(previewTool));
1356
- else if (!enabled && withdraw !== void 0) {
1357
- shown.delete(agent);
1358
- withdraw();
1359
- }
1360
- };
1721
+ const showPreviewTool = previewToggle(previewTool);
1361
1722
  ctx.on("session/event", (session, event) => {
1362
1723
  if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
1363
1724
  timelines.ended(session.id, session, event.seq);
@@ -1395,7 +1756,7 @@ function installHooks(ctx, deps) {
1395
1756
  turn: payload.turn,
1396
1757
  cast
1397
1758
  }) : { ok: true };
1398
- if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request);
1759
+ if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
1399
1760
  else if (ooc === void 0) engine.expectJudgement(owner);
1400
1761
  const queryVector = await store.queryVector(ooc?.request ?? text);
1401
1762
  store.clearNotes();
@@ -1431,10 +1792,10 @@ function installHooks(ctx, deps) {
1431
1792
  else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
1432
1793
  const rules = store.rules();
1433
1794
  if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
1434
- if (ooc !== void 0 && ooc.request !== "") lines.push(store.text("roleplay/ooc-command", { request: ooc.request }));
1795
+ if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
1435
1796
  if (ooc !== void 0 && ooc.request === "") {
1436
1797
  engine.skip(owner);
1437
- lines.push(store.text("roleplay/ooc-empty"));
1798
+ lines.push(store.text("roleplay/ooc-empty", { command: ooc.question ? "/ask" : "/ooc" }));
1438
1799
  }
1439
1800
  if (!verdict.ok) {
1440
1801
  engine.skip(owner);
@@ -1462,107 +1823,6 @@ function currentTurn(agent) {
1462
1823
  return 0;
1463
1824
  }
1464
1825
  //#endregion
1465
- //#region src/host/orchestration/protocol.ts
1466
- const COMMITMENTS = [
1467
- "low",
1468
- "medium",
1469
- "high"
1470
- ];
1471
- const RESULTS = [
1472
- "succeeded",
1473
- "partial",
1474
- "failed"
1475
- ];
1476
- /** What a character is asked to produce; the sub-agent runtime enforces it. */
1477
- const CHARACTER_ACTION_SCHEMA = {
1478
- type: "object",
1479
- properties: {
1480
- intent: {
1481
- type: "string",
1482
- description: "What the character does, or tries to do, now, as an action in one or two sentences, without any speech."
1483
- },
1484
- utterance: {
1485
- type: "string",
1486
- description: "What the character says aloud, word for word and in its own voice, exactly as it will be shown. Leave out when it says nothing."
1487
- },
1488
- commitment: {
1489
- type: "string",
1490
- enum: [...COMMITMENTS],
1491
- description: "How hard the character will keep trying if this does not work out: low gives up at once, high persists."
1492
- }
1493
- },
1494
- required: ["intent", "commitment"],
1495
- additionalProperties: false
1496
- };
1497
- /** The schema for a character acting away from the player: the same answer, which also says in a line what happened, so no second request is needed. */
1498
- const AWAY_ACTION_SCHEMA = {
1499
- ...CHARACTER_ACTION_SCHEMA,
1500
- properties: {
1501
- ...CHARACTER_ACTION_SCHEMA.properties,
1502
- account: {
1503
- type: "string",
1504
- description: "One sentence, in the third person and the past tense, of what came of this, as someone who only saw it from outside would tell it afterwards: no thoughts, no secrets."
1505
- }
1506
- },
1507
- required: [
1508
- "intent",
1509
- "commitment",
1510
- "account"
1511
- ]
1512
- };
1513
- const MAX_ACCOUNT = 300;
1514
- /** @throws {Error} when the value is not a character action. */
1515
- const QUOTE_PAIRS = [
1516
- ["\"", "\""],
1517
- ["“", "”"],
1518
- ["「", "」"],
1519
- ["『", "』"],
1520
- ["«", "»"],
1521
- ["‘", "’"]
1522
- ];
1523
- /** Words said aloud, without the quotation marks a model puts around them: the output puts its own. */
1524
- function unquoted(text) {
1525
- let words = text.trim();
1526
- for (let again = true; again;) {
1527
- again = false;
1528
- for (const [open, close] of QUOTE_PAIRS) if (words.length >= 2 && words.startsWith(open) && words.endsWith(close) && !words.slice(open.length, -close.length).includes(close)) {
1529
- words = words.slice(open.length, words.length - close.length).trim();
1530
- again = true;
1531
- }
1532
- }
1533
- return words;
1534
- }
1535
- const LEAKED_FIELD = /<\/?(?:intent|parameter(?:=\w+)?)>/g;
1536
- /** A model that writes the markup of its call into a field puts the next field's text inside this one. */
1537
- function splitLeakedFields(intent) {
1538
- const at = intent.search(/<parameter=utterance>/);
1539
- if (at === -1) return { intent: intent.replace(LEAKED_FIELD, " ") };
1540
- const spoken = intent.slice(at).replace(LEAKED_FIELD, " ").trim();
1541
- return {
1542
- intent: intent.slice(0, at).replace(LEAKED_FIELD, " "),
1543
- ...spoken === "" ? {} : { utterance: spoken }
1544
- };
1545
- }
1546
- function parseCharacterAction(value) {
1547
- if (typeof value !== "object" || value === null) throw new Error("the character did not answer with an object");
1548
- const { intent: rawIntent, utterance: rawUtterance, commitment, account } = value;
1549
- const { intent, utterance } = typeof rawIntent === "string" && rawUtterance === void 0 ? splitLeakedFields(rawIntent) : {
1550
- intent: rawIntent,
1551
- utterance: rawUtterance
1552
- };
1553
- if (typeof intent !== "string" || intent.trim() === "") throw new Error("the character gave no intent");
1554
- if (!COMMITMENTS.includes(commitment)) throw new Error(`the character gave an unknown commitment "${String(commitment)}"`);
1555
- if (utterance !== void 0 && typeof utterance !== "string") throw new Error("the character's utterance is not text");
1556
- const spoken = utterance === void 0 ? void 0 : unquoted(utterance);
1557
- const told = typeof account === "string" ? account.trim().slice(0, MAX_ACCOUNT) : "";
1558
- return {
1559
- intent: intent.trim(),
1560
- ...spoken === void 0 || spoken === "" ? {} : { utterance: spoken },
1561
- commitment,
1562
- ...told === "" ? {} : { account: told }
1563
- };
1564
- }
1565
- //#endregion
1566
1826
  //#region src/host/orchestration/character-runner.ts
1567
1827
  /**
1568
1828
  * Runs each character as a one-shot child of the game master. It is the character and nothing
@@ -1579,16 +1839,64 @@ function characterRunner(deps) {
1579
1839
  policy: deps.store.settings().memory,
1580
1840
  queryVector: deps.store.queryVector
1581
1841
  }), request.member.character.id) : [];
1582
- return parseCharacterAction(await runChild({
1842
+ const settings = deps.store.settings();
1843
+ const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
1844
+ const result = await runChild({
1583
1845
  parent: deps.parent,
1584
1846
  signal,
1585
- sampling: childSampling(deps.store.settings(), "characters"),
1847
+ sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
1848
+ ...childModel(settings, "characters", named),
1849
+ trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named),
1586
1850
  reasoningEffort: deps.store.settings().reasoning.children,
1587
1851
  persona: brief.persona,
1588
1852
  prompt: brief.prompt,
1589
1853
  tools,
1590
- result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA
1591
- }));
1854
+ maxCalls: deps.store.settings().memory.lookupCalls,
1855
+ result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
1856
+ unenforced: ["thought"]
1857
+ });
1858
+ return parseCharacterAction(result);
1859
+ };
1860
+ }
1861
+ /** What the character was reminded of and why, for the run's record, when the recall said why. */
1862
+ function recalledOf(request) {
1863
+ const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
1864
+ return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
1865
+ clarity,
1866
+ turn,
1867
+ text,
1868
+ why
1869
+ })) };
1870
+ }
1871
+ const ANSWER_SCHEMA = {
1872
+ type: "object",
1873
+ properties: { answer: {
1874
+ type: "string",
1875
+ description: "The answer to the player, in plain words, in a few sentences."
1876
+ } },
1877
+ required: ["answer"],
1878
+ additionalProperties: false
1879
+ };
1880
+ /**
1881
+ * 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
1882
+ * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
1883
+ */
1884
+ function answerRunner(deps) {
1885
+ return async (request, signal) => {
1886
+ const brief = deps.boundaries().characterContext.brief(request);
1887
+ return (await runChild({
1888
+ parent: deps.parent,
1889
+ signal,
1890
+ sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
1891
+ ...childModel(deps.store.settings(), "records"),
1892
+ trace: childTrace(deps.store, "records", "answer to the player"),
1893
+ reasoningEffort: deps.store.settings().reasoning.children,
1894
+ persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
1895
+ prompt: brief.prompt,
1896
+ tools: [],
1897
+ maxCalls: 3,
1898
+ result: ANSWER_SCHEMA
1899
+ })).answer;
1592
1900
  };
1593
1901
  }
1594
1902
  //#endregion
@@ -1708,6 +2016,8 @@ async function authorPlot(parent, store, turn, signal) {
1708
2016
  parent,
1709
2017
  signal,
1710
2018
  sampling: childSampling(store.settings(), "authoring"),
2019
+ ...childModel(store.settings(), "authoring"),
2020
+ trace: childTrace(store, "authoring", "plot author"),
1711
2021
  persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
1712
2022
  reasoningEffort: store.settings().reasoning.children,
1713
2023
  result: RESULT,
@@ -1749,6 +2059,7 @@ const INTRODUCE_TOOL = "introduce_thing";
1749
2059
  const TIME_TOOL = "advance_time";
1750
2060
  const PREVIEW_TOOL = "preview_scene";
1751
2061
  const RULING_TOOL = "ooc_ruling";
2062
+ const ANSWER_TOOL = "ooc_answer";
1752
2063
  const JUDGE_TOOL = "judge_action";
1753
2064
  const PLOT_TOOL = "record_plot_progress";
1754
2065
  const AUTHOR_PLOT_TOOL = "author_plot";
@@ -1760,7 +2071,7 @@ function failures(list) {
1760
2071
  return list.length === 0 ? [] : [
1761
2072
  "",
1762
2073
  "Could not act:",
1763
- ...list.map((failure) => `- ${failure.character} (${failure.name}): ${failure.reason}`)
2074
+ ...list.map((failure) => failure.technical === true ? `- ${failure.character} (${failure.name}): no decision came back. That is a fault of the system, not something that happened in the story: nothing is recorded for ${failure.name} this round, so write nothing for them and say nothing about why` : `- ${failure.character} (${failure.name}): ${failure.reason}`)
1764
2075
  ];
1765
2076
  }
1766
2077
  function renderAttempt(attempt) {
@@ -1844,16 +2155,16 @@ function createTools$1(deps) {
1844
2155
  name: ACTIVATE_TOOL,
1845
2156
  description: "Let the characters act: one round of the turn. Each character asked is asked, separately and at the same time, what it intends to do and say in the situation you describe and how committed it is. Call it after reading what the player did, and again for a later round only when the story genuinely needs the characters to react to what just happened; the number of rounds for one player message is limited.",
1846
2157
  parameters: {
1847
- situation: {
1848
- type: "string",
1849
- required: true,
1850
- 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."
1851
- },
1852
2158
  characters: {
1853
2159
  type: "array",
1854
2160
  required: true,
1855
2161
  items: { type: "string" },
1856
2162
  description: "Keys of the characters to ask, chosen by you from the scene (where each is, what each is doing). Ask only those the moment reaches: those in the same place, and those elsewhere who can plainly see, hear or are summoned; a character elsewhere perceives nothing by itself. Never the whole cast. In a later round ask only those the moment calls for."
2163
+ },
2164
+ situation: {
2165
+ type: "string",
2166
+ required: true,
2167
+ 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."
1857
2168
  }
1858
2169
  },
1859
2170
  output: {
@@ -1882,10 +2193,6 @@ function createTools$1(deps) {
1882
2193
  name: RESOLVE_TOOL,
1883
2194
  description: "Decide what actually happens to each character that acted in the current round, from their intents and the scene only. Intents can conflict; settle them consistently. A character whose intent fails and who was highly committed gets one more chance, and you resolve that attempt too. The player's character is not asked to act, but you may include an outcome for it (its key is in the scene) when what the player did moves it somewhere or has it handle things; when nobody else needs to react (the player just walks somewhere, picks something up), call this with only that outcome, without activate_characters. When nobody retries, the round is recorded and you decide whether another round is needed or the turn goes back to the player.",
1884
2195
  parameters: {
1885
- elapsed_seconds: {
1886
- type: "integer",
1887
- description: "How long this round took in the story, in seconds:: a few seconds for a remark, a minute or two for a conversation, longer for work or a journey. Left out, the chat's default applies. Not when the story's time follows the wall clock."
1888
- },
1889
2196
  outcomes: {
1890
2197
  type: "array",
1891
2198
  required: true,
@@ -2032,6 +2339,10 @@ function createTools$1(deps) {
2032
2339
  }
2033
2340
  }
2034
2341
  }
2342
+ },
2343
+ elapsed_seconds: {
2344
+ type: "integer",
2345
+ description: "How long this round took in the story, in seconds:: a few seconds for a remark, a minute or two for a conversation, longer for work or a journey. Left out, the chat's default applies. Not when the story's time follows the wall clock."
2035
2346
  }
2036
2347
  },
2037
2348
  output: {
@@ -2336,6 +2647,11 @@ function createTools$1(deps) {
2336
2647
  name: TIME_TOOL,
2337
2648
  description: "Skip ahead in the story's time, between rounds: the player's character sleeps till morning, waits, or travels for days. Say either how long (by_minutes) or until when (until_time, and days_later for a later day). Time does not otherwise pass faster than the rounds take; use this only for a stretch that is summarised rather than played. Nothing else changes: if the skip changes what characters are doing or where they are, run a round for them afterwards. Not available when the story's time follows the wall clock.",
2338
2649
  parameters: {
2650
+ reason: {
2651
+ type: "string",
2652
+ required: true,
2653
+ description: "What happens in the time that passes, in a sentence (\"they sleep\", \"the ferry crosses\")."
2654
+ },
2339
2655
  by_minutes: {
2340
2656
  type: "integer",
2341
2657
  description: "How many minutes to skip."
@@ -2347,11 +2663,6 @@ function createTools$1(deps) {
2347
2663
  days_later: {
2348
2664
  type: "integer",
2349
2665
  description: "With until_time: that many days after today (0 is later today, 1 is tomorrow)."
2350
- },
2351
- reason: {
2352
- type: "string",
2353
- required: true,
2354
- description: "What happens in the time that passes, in a sentence (\"they sleep\", \"the ferry crosses\")."
2355
2666
  }
2356
2667
  },
2357
2668
  output: {
@@ -2438,6 +2749,27 @@ function createTools$1(deps) {
2438
2749
  return Promise.resolve(record(deps.engine.rule(owner, args.legal, args.reason)));
2439
2750
  }
2440
2751
  });
2752
+ const answer = defineTool({
2753
+ name: ANSWER_TOOL,
2754
+ description: "Have the player's out-of-character question answered, as the very first thing of a question turn. You do not write the answer: it is written from what the player's character knows (what it remembers, knows to exist, carries and sees where it is), so that nothing hidden is given away. Nothing in the story changes, nobody is asked to act and time does not pass.",
2755
+ parameters: {},
2756
+ output: {
2757
+ schema: { type: "json" },
2758
+ render: () => [{
2759
+ type: "text",
2760
+ text: `The player is shown the answer. Now call ${NARRATE_TOOL} with no segments.`
2761
+ }]
2762
+ },
2763
+ isConcurrencySafe: () => false,
2764
+ async execute(_args, exec) {
2765
+ const { agent, owner } = ownerOf(exec.agent);
2766
+ return record(await deps.engine.answer(owner, answerRunner({
2767
+ parent: agent,
2768
+ boundaries: deps.boundaries,
2769
+ store: storeOf(owner.chat)
2770
+ }), exec.signal));
2771
+ }
2772
+ });
2441
2773
  return [
2442
2774
  defineTool({
2443
2775
  name: JUDGE_TOOL,
@@ -2448,6 +2780,10 @@ function createTools$1(deps) {
2448
2780
  required: true,
2449
2781
  description: "First, go through every rule the scene lists, one by one, in a few words each: does what the character tries need what the rule excludes? The rules are literal. Then whether it is viable here. Write \"no rules listed\" when there are none."
2450
2782
  },
2783
+ at: {
2784
+ type: "string",
2785
+ description: "The key of the place where the action happens, only when the player says it happens at a particular place (talking to the baker in the market, searching the cellar) rather than where the character is. If the character is somewhere else the action cannot work: it has to go there first. Leave it out when the action happens where the character is, and when the player is going somewhere (the journey is its own action)."
2786
+ },
2451
2787
  allowed: {
2452
2788
  type: "boolean",
2453
2789
  required: true,
@@ -2463,17 +2799,18 @@ function createTools$1(deps) {
2463
2799
  schema: { type: "json" },
2464
2800
  render: (_args, value) => [{
2465
2801
  type: "text",
2466
- text: value.allowed ? `Judged: it can work. Now call ${PREVIEW_TOOL} (when the scene asks for it) and ${ACTIVATE_TOOL}, describing only what the character does.` : `Judged: it cannot work. Play the failed attempt: ${RESOLVE_TOOL} with one outcome for the player's character (result failed, one sentence: what it does, what comes of it, why not) and nothing else, then ${NARRATE_TOOL}. Narrate what a witness would see of the attempt, never the effect the player claimed.`
2802
+ text: value.allowed ? `Judged: it can work. Now call ${PREVIEW_TOOL} (when the scene asks for it) and ${ACTIVATE_TOOL}, describing only what the character does.` : `Judged: it cannot work${value.elsewhere === true ? ` (${value.reason})` : ""}. Play the failed attempt: ${RESOLVE_TOOL} with one outcome for the player's character (result failed, one sentence: what it does, what comes of it, why not) and nothing else, then ${NARRATE_TOOL}. Narrate what a witness would see of the attempt, never the effect the player claimed.`
2467
2803
  }]
2468
2804
  },
2469
2805
  isConcurrencySafe: () => false,
2470
2806
  execute(args, exec) {
2471
2807
  const { owner } = ownerOf(exec.agent);
2472
- return Promise.resolve(record(deps.engine.judge(owner, args.allowed, args.reason)));
2808
+ return Promise.resolve(record(deps.engine.judge(owner, args.allowed, args.reason, args.at)));
2473
2809
  }
2474
2810
  }),
2475
2811
  preview,
2476
2812
  ruling,
2813
+ answer,
2477
2814
  activate,
2478
2815
  resolve,
2479
2816
  skip,
@@ -2608,12 +2945,160 @@ function rerankMemories(deps) {
2608
2945
  };
2609
2946
  }
2610
2947
  //#endregion
2948
+ //#region src/host/orchestration/after-turn.ts
2949
+ /** Something made up that has waited this many turns is fitted into the world even if few are waiting. */
2950
+ const STALE_AFTER_TURNS = 4;
2951
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
2952
+ /**
2953
+ * The background work that follows a delivered turn and writes to the story, none of which the turn waits for: fitting in what was made
2954
+ * up, the decisions of organisations, and the judging of the statements triggers wait on. Each runs one at a time per chat, within the
2955
+ * limits of the chat's settings, and a failure is reported and leaves the story as it was.
2956
+ */
2957
+ var AfterTurnJobs = class {
2958
+ deps;
2959
+ consolidating = /* @__PURE__ */ new Set();
2960
+ strategizing = /* @__PURE__ */ new Set();
2961
+ judging = /* @__PURE__ */ new Set();
2962
+ constructor(deps) {
2963
+ this.deps = deps;
2964
+ }
2965
+ start(owner, cancel) {
2966
+ this.consolidate(owner, cancel);
2967
+ this.strategize(owner, cancel);
2968
+ this.judge(owner, cancel);
2969
+ }
2970
+ /** Fit what was made up into the rest of the world, when enough of it is waiting or some has waited long. */
2971
+ consolidate(owner, cancel) {
2972
+ const store = this.deps.stores(owner.chat);
2973
+ if (store === void 0 || this.consolidating.has(owner.chat)) return;
2974
+ const { authoring } = store.settings();
2975
+ const pending = store.story.consolidation.pending();
2976
+ if (!authoring.enabled || pending.length === 0) return;
2977
+ if (pending.length < authoring.consolidateAfter && !pending.some((item) => owner.turn - item.createdTurn >= STALE_AFTER_TURNS)) return;
2978
+ this.consolidating.add(owner.chat);
2979
+ this.deps.track(owner.chat, this.deps.boundaries().author.consolidate({
2980
+ chat: owner.chat,
2981
+ turn: owner.turn,
2982
+ store
2983
+ }, cancel).then(() => {
2984
+ this.deps.written(owner.chat);
2985
+ }).catch((error) => {
2986
+ if (!cancel.aborted) this.deps.problem(`made-up characters and places were not fitted into the world: ${messageOf(error)}`);
2987
+ }).finally(() => {
2988
+ this.consolidating.delete(owner.chat);
2989
+ }));
2990
+ }
2991
+ /** The organisations whose time has come decide what they do; the strategist holds the limits. */
2992
+ strategize(owner, cancel) {
2993
+ const store = this.deps.stores(owner.chat);
2994
+ if (store === void 0 || this.strategizing.has(owner.chat) || store.settings().factions.perTurn === 0) return;
2995
+ this.strategizing.add(owner.chat);
2996
+ this.deps.track(owner.chat, this.deps.boundaries().strategist.strategize({
2997
+ chat: owner.chat,
2998
+ turn: owner.turn,
2999
+ store
3000
+ }, cancel).then((report) => {
3001
+ if (report.acted.length > 0) this.deps.written(owner.chat);
3002
+ }).catch((error) => {
3003
+ if (!cancel.aborted) this.deps.problem(`organisations were not asked what they do: ${messageOf(error)}`);
3004
+ }).finally(() => {
3005
+ this.strategizing.delete(owner.chat);
3006
+ }));
3007
+ }
3008
+ /** The statements that triggers wait on are judged; a trigger fires from the verdict at the next look. */
3009
+ judge(owner, cancel) {
3010
+ const store = this.deps.stores(owner.chat);
3011
+ if (store === void 0 || this.judging.has(owner.chat) || !store.settings().triggers.enabled || store.settings().triggers.judgedPerTurn === 0) return;
3012
+ this.judging.add(owner.chat);
3013
+ this.deps.track(owner.chat, this.deps.boundaries().judge.judge({
3014
+ chat: owner.chat,
3015
+ turn: owner.turn,
3016
+ store
3017
+ }, cancel).catch((error) => {
3018
+ if (!cancel.aborted) this.deps.problem(`the statements triggers wait on were not judged: ${messageOf(error)}`);
3019
+ }).finally(() => {
3020
+ this.judging.delete(owner.chat);
3021
+ }));
3022
+ }
3023
+ };
3024
+ //#endregion
3025
+ //#region src/host/orchestration/whereabouts.ts
3026
+ const within = (inner, outer, places) => {
3027
+ const byId = new Map(places.map((place) => [place.id, place]));
3028
+ const seen = /* @__PURE__ */ new Set();
3029
+ for (let at = inner; at !== void 0 && !seen.has(at.id); at = at.parentId === void 0 ? void 0 : byId.get(at.parentId)) {
3030
+ if (at.id === outer.id) return true;
3031
+ seen.add(at.id);
3032
+ }
3033
+ return false;
3034
+ };
3035
+ /**
3036
+ * Compares the place an action is said to happen at (by key) with where the character is. Only a proven mismatch counts: a character that is
3037
+ * nowhere, or a world without places, is no evidence, and a place that contains the other (a room and its building) is the same for this.
3038
+ */
3039
+ function whereabouts(places, here, at) {
3040
+ const target = places.find((place) => locationKey(place) === at);
3041
+ if (target === void 0) return { kind: "unknown" };
3042
+ if (here === void 0) return { kind: "unplaced" };
3043
+ return within(here, target, places) || within(target, here, places) ? { kind: "here" } : {
3044
+ kind: "elsewhere",
3045
+ target,
3046
+ here
3047
+ };
3048
+ }
3049
+ //#endregion
2611
3050
  //#region src/host/orchestration/turn-engine.ts
2612
3051
  const MAX_OBJECTIONS = 3;
2613
3052
  /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
2614
3053
  const MAX_ROUND_SECONDS = 86400;
2615
- /** Something made up that has waited this many turns is fitted into the world even if few are waiting. */
2616
- const STALE_AFTER_TURNS = 4;
3054
+ /**
3055
+ * A model sometimes sends who speaks as a segment of its own (an utterance with no character whose text is the character's key or name) followed by the words with no
3056
+ * character either. When the label is exactly a character of the scene, the label is folded into the words that follow it.
3057
+ */
3058
+ function foldSpeakerLabels(segments, cast) {
3059
+ const found = (label) => {
3060
+ const wanted = label.trim().normalize("NFKC").toLowerCase();
3061
+ return wanted === "" ? void 0 : cast.find((member) => member.key.toLowerCase() === wanted || member.character.name.normalize("NFKC").toLowerCase() === wanted);
3062
+ };
3063
+ const folded = [];
3064
+ for (let index = 0; index < segments.length; index += 1) {
3065
+ const segment = segments[index];
3066
+ const next = segments[index + 1];
3067
+ const speaker = segment.type === "utterance" && (segment.character ?? "") === "" && next?.type === "utterance" && (next.character ?? "") === "" ? found(segment.text) : void 0;
3068
+ if (speaker === void 0) {
3069
+ folded.push(segment);
3070
+ continue;
3071
+ }
3072
+ folded.push({
3073
+ ...next,
3074
+ character: speaker.key
3075
+ });
3076
+ index += 1;
3077
+ }
3078
+ return folded;
3079
+ }
3080
+ /** How alike two situations have to be for a round about the second to bring nothing new, by the share of three-letter pieces they have in common. */
3081
+ const SAME_SITUATION = .85;
3082
+ const pieces = (text) => {
3083
+ const found = /* @__PURE__ */ new Set();
3084
+ const chars = [...text];
3085
+ for (let index = 0; index + 3 <= chars.length; index += 1) found.add(chars.slice(index, index + 3).join(""));
3086
+ return found;
3087
+ };
3088
+ /** Whether the same characters (or some of them) are asked about a situation that is, but for a few words, one they were already asked about in the turn. */
3089
+ function repeatsEarlier(signature, asked) {
3090
+ const [keys = "", text = ""] = signature.split("|");
3091
+ const now = new Set(keys.split(","));
3092
+ const mine = pieces(text);
3093
+ return asked.some((earlier) => {
3094
+ const [before = "", was = ""] = earlier.split("|");
3095
+ if (![...now].every((key) => before.split(",").includes(key))) return false;
3096
+ const theirs = pieces(was);
3097
+ const shared = [...mine].filter((piece) => theirs.has(piece)).length;
3098
+ const union = mine.size + theirs.size - shared;
3099
+ return union === 0 || shared / union >= SAME_SITUATION;
3100
+ });
3101
+ }
2617
3102
  /** The game master is asked to correct its output this many times before it is corrected for it. */
2618
3103
  const MAX_REFUSALS = 2;
2619
3104
  /** 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. */
@@ -2640,8 +3125,7 @@ var TurnEngine = class {
2640
3125
  objections = /* @__PURE__ */ new Map();
2641
3126
  /** What runs in the background of each chat and writes to its story, other than the records: fitting in what was made up, and the characters away. */
2642
3127
  working = /* @__PURE__ */ new Map();
2643
- /** Chats whose made-up characters and places are being fitted into the world now: one run at a time. */
2644
- consolidating = /* @__PURE__ */ new Set();
3128
+ afterTurn;
2645
3129
  /** Chats whose characters away from the player are being asked about what fell due: one run at a time. */
2646
3130
  offstage = /* @__PURE__ */ new Set();
2647
3131
  constructor(boundaries, stores, problem = () => void 0, written = () => void 0) {
@@ -2649,17 +3133,93 @@ var TurnEngine = class {
2649
3133
  this.stores = stores;
2650
3134
  this.problem = problem;
2651
3135
  this.written = written;
3136
+ this.afterTurn = new AfterTurnJobs({
3137
+ boundaries: () => this.boundaries(),
3138
+ stores: (chat) => this.stores(chat),
3139
+ track: (chat, job) => {
3140
+ this.track(chat, job);
3141
+ },
3142
+ problem: (message) => {
3143
+ this.problem(message);
3144
+ },
3145
+ written: (chat) => {
3146
+ this.written(chat);
3147
+ }
3148
+ });
2652
3149
  }
2653
3150
  /**
2654
3151
  * The turn is an out-of-character command of the player: nobody is asked to act and no preview is shown. The game master rules on
2655
3152
  * whether it is allowed (`rule`) and, if so, makes it happen with outcomes for any characters, with the world's tools, and says what the player perceives.
2656
3153
  */
2657
- beginOoc(owner, request) {
3154
+ beginOoc(owner, request, question = false) {
2658
3155
  const state = this.stateFor(owner);
2659
- state.ooc = { request };
3156
+ state.ooc = {
3157
+ request,
3158
+ ...question ? { question: true } : {}
3159
+ };
2660
3160
  state.previewWanted = false;
2661
3161
  }
2662
3162
  /**
3163
+ * The answer to an out-of-character question, which is the whole of that turn: nothing in the story changes and nobody is asked to act. It is not the game
3164
+ * master's to write, who knows what the player's character does not: it comes from what the player's character knows (what it remembers, knows exists, has
3165
+ * on it and sees where it is), so that nothing hidden can be given away.
3166
+ * @throws {Error} when the turn is not a question, it was already answered, or the answer is empty.
3167
+ */
3168
+ async answer(owner, run, signal) {
3169
+ const state = this.stateFor(owner);
3170
+ if (state.ooc?.question !== true) throw new Error("this turn is not an out-of-character question: there is nothing to answer");
3171
+ if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
3172
+ const text = (await run(await this.askedRequest(owner, state.ooc.request, signal), signal)).trim();
3173
+ if (text === "") throw new Error("the answer is empty");
3174
+ if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
3175
+ state.ooc.ruling = {
3176
+ legal: true,
3177
+ note: text.length > 1200 ? `${text.slice(0, 1199)}…` : text,
3178
+ question: true
3179
+ };
3180
+ state.phase = "between";
3181
+ return state.ooc.ruling;
3182
+ }
3183
+ /** What the player's character is given to answer a question with: the same as a character is given to act, with the question as the moment. */
3184
+ async askedRequest(owner, question, signal) {
3185
+ const store = this.storeOf(owner);
3186
+ const cast = store.cast();
3187
+ const member = cast.find((candidate) => candidate.character.control === "player");
3188
+ if (member === void 0) throw new Error("there is no player's character to answer for");
3189
+ const queryVector = await store.queryVector(question, signal);
3190
+ const memories = await this.boundaries().recaller.recall({
3191
+ member,
3192
+ situation: question,
3193
+ turn: owner.turn,
3194
+ policy: store.settings().memory,
3195
+ ...queryVector === void 0 ? {} : { queryVector }
3196
+ }, store.story, signal);
3197
+ const place = member.place === void 0 ? void 0 : store.place(member.place.location.id);
3198
+ const company = place === void 0 ? cast : place.here;
3199
+ const relationships = this.knownRelationships(member, company, question, cast, store);
3200
+ const carrying = store.carried(member.character.id);
3201
+ const affiliations = store.affiliations(member.character.id);
3202
+ const tracked = store.trackedFor(member.character.id, company.map((entry) => entry.character.id));
3203
+ return {
3204
+ member,
3205
+ cast,
3206
+ situation: question,
3207
+ attempt: 1,
3208
+ language: store.settings().prompts.language,
3209
+ turn: owner.turn,
3210
+ lookup: false,
3211
+ text: (id, variables) => store.text(id, variables),
3212
+ time: store.time(owner.turn),
3213
+ knowledge: store.knowledge(member.character.id, owner.turn, company.map((entry) => entry.character.id)),
3214
+ ...tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
3215
+ ...place === void 0 ? {} : { place },
3216
+ ...relationships.length === 0 ? {} : { relationships },
3217
+ ...carrying.length === 0 ? {} : { carrying },
3218
+ ...affiliations.length === 0 ? {} : { affiliations },
3219
+ ...memories.length === 0 ? {} : { memories }
3220
+ };
3221
+ }
3222
+ /**
2663
3223
  * The game master's ruling on an out-of-character command: it is legal unless it breaks the rules of the world or the player's own. The reason is
2664
3224
  * what the player is told. Either way the turn goes on to its output; only a legal ruling lets the command change anything.
2665
3225
  * @throws {Error} when the turn is not an out-of-character command, it was already ruled on, or the reason is empty or too long.
@@ -2667,6 +3227,7 @@ var TurnEngine = class {
2667
3227
  rule(owner, legal, reason) {
2668
3228
  const state = this.stateFor(owner);
2669
3229
  if (state.ooc === void 0) throw new Error("this turn is not an out-of-character command: there is nothing to rule on");
3230
+ if (state.ooc.question === true) throw new Error("this turn is an out-of-character question: answer it with ooc_answer");
2670
3231
  if (state.ooc.ruling !== void 0) throw new Error("this command was already ruled on");
2671
3232
  const note = reason.trim();
2672
3233
  if (note === "") throw new Error("give the reason, in plain words to the player");
@@ -2681,15 +3242,34 @@ var TurnEngine = class {
2681
3242
  /**
2682
3243
  * The game master judges what the player's character tries, before anything else in an ordinary turn: it works unless it is not viable or it breaks a rule of the
2683
3244
  * world or of the player. What does not work is played as a failed attempt for the player's character: nobody is asked to act on it.
2684
- * @throws {Error} when the turn is not an ordinary one, was already judged, or the reason is empty.
3245
+ * When the action is said to happen at a place (`at`, a place key) and the character is somewhere else, it does not work whatever was judged: the character has to get there first.
3246
+ * @throws {Error} when the turn is not an ordinary one, was already judged, the reason is empty, or `at` is not a place.
2685
3247
  */
2686
- judge(owner, allowed, reason) {
3248
+ judge(owner, allowed, reason, at) {
2687
3249
  const state = this.stateFor(owner);
2688
- if (state.ooc !== void 0) throw new Error("this turn is an out-of-character command: rule on it with ooc_ruling");
3250
+ if (state.ooc !== void 0) throw new Error("this turn is an out-of-character " + (state.ooc.question === true ? "question: answer it with ooc_answer" : "command: rule on it with ooc_ruling"));
2689
3251
  if (state.phase !== "idle") throw new Error("the action is judged first, before anything else");
2690
3252
  if (state.judgement !== void 0) throw new Error("the action was already judged");
2691
3253
  const why = reason.trim();
2692
3254
  if (why === "") throw new Error("give the reason: what the character tries, and the rule or the fact that decides it");
3255
+ const place = at?.trim() ?? "";
3256
+ if (place !== "") {
3257
+ const store = this.storeOf(owner);
3258
+ const player = store.cast().find((member) => member.character.control === "player");
3259
+ const found = whereabouts(store.story.locations.list(), player?.place?.location, place);
3260
+ if (found.kind === "unknown") throw new Error(`there is no place "${place}" (list_locations shows the keys): name the place where the action happens, or leave "at" out when it happens where the character is`);
3261
+ if (found.kind === "elsewhere") {
3262
+ const name = player?.character.name ?? "The character";
3263
+ state.judgement = {
3264
+ allowed: false,
3265
+ reason: `${name} is at ${found.here.name}, not at ${found.target.name} where this happens: ${name} has to go there first`
3266
+ };
3267
+ return {
3268
+ ...state.judgement,
3269
+ elsewhere: true
3270
+ };
3271
+ }
3272
+ }
2693
3273
  state.judgement = {
2694
3274
  allowed,
2695
3275
  reason: why
@@ -2707,6 +3287,7 @@ var TurnEngine = class {
2707
3287
  /** Why an out-of-character command may not change anything yet, when it may not. */
2708
3288
  oocBlock(state) {
2709
3289
  if (state.ooc === void 0) return void 0;
3290
+ if (state.ooc.question === true) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
2710
3291
  if (state.ooc.ruling === void 0) return "this turn is an out-of-character command: rule on it first with ooc_ruling";
2711
3292
  return state.ooc.ruling.legal ? void 0 : "the command was refused: nothing changes; call narrate with no segments to tell the player";
2712
3293
  }
@@ -2720,7 +3301,7 @@ var TurnEngine = class {
2720
3301
  */
2721
3302
  async activate(owner, input, run, signal) {
2722
3303
  const state = this.stateFor(owner);
2723
- if (state.ooc !== void 0) throw new Error("an out-of-character command asks nobody to act: decree what happens with resolve_round, or narrate");
3304
+ 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");
2724
3305
  if (state.phase !== "idle" && state.phase !== "between") throw new Error(this.explain(state, "activate_characters"));
2725
3306
  if (this.judgeDue(state)) throw new Error(this.explain(state, "activate_characters"));
2726
3307
  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`);
@@ -2739,7 +3320,7 @@ var TurnEngine = class {
2739
3320
  if (keys.length === 0) throw new Error("there is no character to activate");
2740
3321
  if (keys.length > most) throw new Error(`${keys.length} characters were asked, which is more than one round allows (${most}): ask only those the moment actually reaches, and the others in a later round if the story comes to them`);
2741
3322
  const signature = `${[...keys].sort().join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
2742
- if (state.asked.includes(signature)) throw new Error("the same characters were already asked about the same situation in this message, so nothing new would come of it: say what changed, ask others, or deliver the output with narrate");
3323
+ if (repeatsEarlier(signature, state.asked)) throw new Error("the same characters were already asked about the same situation in this message, so nothing new would come of it: say what changed, ask others, or deliver the output with narrate");
2743
3324
  state.situation = situation;
2744
3325
  state.cast = cast;
2745
3326
  state.recalled.clear();
@@ -2876,7 +3457,7 @@ var TurnEngine = class {
2876
3457
  */
2877
3458
  preview(owner, text) {
2878
3459
  const state = this.stateFor(owner);
2879
- if (state.ooc !== void 0) throw new Error("an out-of-character command shows no preview: rule on it with ooc_ruling");
3460
+ 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"));
2880
3461
  if (this.judgeDue(state)) throw new Error("judge the action first with judge_action");
2881
3462
  if (!this.storeOf(owner).settings().preview.enabled) throw new Error("this chat shows no preview: go on with activate_characters");
2882
3463
  if (state.previewed) throw new Error("a preview was already shown for this message: go on with activate_characters");
@@ -2940,6 +3521,7 @@ var TurnEngine = class {
2940
3521
  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)`);
2941
3522
  state.addressed = [...new Set(addressed)];
2942
3523
  if (state.ooc !== void 0) {
3524
+ if (state.ooc.question === true && segments.length > 0) throw new Error("a question is answered with ooc_answer: deliver no segments, the player is shown the answer");
2943
3525
  if (state.ooc.ruling?.legal !== true && segments.length > 0) throw new Error("the command was refused: deliver no segments, the player is told why");
2944
3526
  if (segments.some((segment) => segment.type === "utterance")) throw new Error("nobody was asked to speak in an out-of-character command: narrate only what the player perceives");
2945
3527
  return await this.deliver(owner, state, segments.map((segment) => ({
@@ -2957,7 +3539,7 @@ var TurnEngine = class {
2957
3539
  if (written === void 0) throw new Error("deliver the output: give its segments");
2958
3540
  return await this.deliver(owner, state, written, true, run);
2959
3541
  }
2960
- const typed = segments.map((segment) => segment.type === "utterance" ? {
3542
+ const typed = foldSpeakerLabels(segments, state.cast).map((segment) => segment.type === "utterance" ? {
2961
3543
  type: "utterance",
2962
3544
  character: segment.character ?? "",
2963
3545
  name: state.cast.find((member) => member.key === segment.character)?.character.name ?? segment.character ?? "",
@@ -3047,30 +3629,6 @@ var TurnEngine = class {
3047
3629
  return this.stores(owner.chat)?.story.consolidation.pending().length ?? 0;
3048
3630
  }
3049
3631
  /**
3050
- * Fit what was made up into the rest of the world in the background, when enough of it is waiting or some
3051
- * has waited long: the turn does not wait for it, and a failed run leaves everything queued for the next.
3052
- */
3053
- consolidateIfDue(owner, state) {
3054
- const store = this.stores(owner.chat);
3055
- if (store === void 0 || this.consolidating.has(owner.chat)) return;
3056
- const { authoring } = store.settings();
3057
- const pending = store.story.consolidation.pending();
3058
- if (!authoring.enabled || pending.length === 0) return;
3059
- if (pending.length < authoring.consolidateAfter && !pending.some((item) => owner.turn - item.createdTurn >= STALE_AFTER_TURNS)) return;
3060
- this.consolidating.add(owner.chat);
3061
- this.track(owner.chat, this.boundaries().author.consolidate({
3062
- chat: owner.chat,
3063
- turn: owner.turn,
3064
- store
3065
- }, state.cancel.signal).then(() => {
3066
- this.written(owner.chat);
3067
- }).catch((error) => {
3068
- if (!state.cancel.signal.aborted) this.problem(`made-up characters and places were not fitted into the world: ${error instanceof Error ? error.message : String(error)}`);
3069
- }).finally(() => {
3070
- this.consolidating.delete(owner.chat);
3071
- }));
3072
- }
3073
- /**
3074
3632
  * After the turn, in the background: characters away from the player's character, for whom something fell due (a commitment whose
3075
3633
  * time has come, a deadline that passed), are asked what they do about it, as many as the chat allows. What they decide is applied
3076
3634
  * (their activity, and a move to where the commitment was when they mean to keep it) and recorded as a round only they perceive;
@@ -3091,7 +3649,7 @@ var TurnEngine = class {
3091
3649
  }));
3092
3650
  }
3093
3651
  async runOffScene(owner, state, store, due, limit, run) {
3094
- const { summary, perCharacter } = store.settings().offstage;
3652
+ const { summary, perCharacter, joint } = store.settings().offstage;
3095
3653
  let budget = limit;
3096
3654
  const acted = /* @__PURE__ */ new Map();
3097
3655
  for (const item of due) {
@@ -3101,18 +3659,22 @@ var TurnEngine = class {
3101
3659
  if (keys.length === 0) continue;
3102
3660
  budget -= keys.length;
3103
3661
  for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
3104
- const asked = {
3105
- ...state,
3106
- situation: item.text,
3107
- history: [],
3108
- recalled: /* @__PURE__ */ new Map()
3109
- };
3110
- delete asked.first;
3111
- delete asked.second;
3112
- const attempt = await this.runAttempt(owner, 1, keys, cast, asked, run, state.cancel.signal, summary);
3113
- if (attempt.reports.length === 0) continue;
3662
+ const reports = [];
3663
+ for (const group of joint ? keys.map((key) => [key]) : [keys]) {
3664
+ const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
3665
+ const asked = {
3666
+ ...state,
3667
+ situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
3668
+ history: [],
3669
+ recalled: /* @__PURE__ */ new Map()
3670
+ };
3671
+ delete asked.first;
3672
+ delete asked.second;
3673
+ reports.push(...(await this.runAttempt(owner, 1, group, cast, asked, run, state.cancel.signal, summary)).reports);
3674
+ }
3675
+ if (reports.length === 0) continue;
3114
3676
  const where = item.place;
3115
- const moves = new Map(attempt.reports.flatMap((report) => {
3677
+ const moves = new Map(reports.flatMap((report) => {
3116
3678
  if (report.commitment === "low" || where === void 0) return [];
3117
3679
  const check = store.checkMove(report.character, {
3118
3680
  location: where,
@@ -3120,7 +3682,7 @@ var TurnEngine = class {
3120
3682
  });
3121
3683
  return check.ok ? [[report.character, check]] : [];
3122
3684
  }));
3123
- store.commit(attempt.reports.flatMap((report) => {
3685
+ store.commit(reports.flatMap((report) => {
3124
3686
  const member = cast.find((candidate) => candidate.key === report.character);
3125
3687
  const move = moves.get(report.character);
3126
3688
  return member === void 0 ? [] : [{
@@ -3141,7 +3703,7 @@ var TurnEngine = class {
3141
3703
  to: time.now,
3142
3704
  zone: time.zone
3143
3705
  },
3144
- entries: attempt.reports.map((report) => {
3706
+ entries: reports.map((report) => {
3145
3707
  const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
3146
3708
  const move = moves.get(report.character);
3147
3709
  return {
@@ -3163,7 +3725,7 @@ var TurnEngine = class {
3163
3725
  store.markHandled([item.key]);
3164
3726
  this.write(owner, state);
3165
3727
  if (summary && this.states.get(owner.chat) === state) {
3166
- const lines = attempt.reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3728
+ const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3167
3729
  store.addNote("away", owner.turn, lines);
3168
3730
  }
3169
3731
  }
@@ -3282,10 +3844,11 @@ var TurnEngine = class {
3282
3844
  return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
3283
3845
  }
3284
3846
  explain(state, attempted) {
3847
+ if (state.ooc?.question === true && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3285
3848
  if (state.ooc !== void 0 && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character command: rule on it first with ooc_ruling" : state.ooc.ruling.legal ? "make the command happen with resolve_round, expand_world or advance_time, then call narrate with what the player perceives (narration only)" : "the command was refused: call narrate with no segments";
3286
3849
  const waiting = (attempt) => (attempt?.reports ?? []).map((report) => report.character).join(", ");
3287
3850
  switch (state.phase) {
3288
- case "idle": return this.judgeDue(state) ? "call judge_action first: does what the player's character tries work? It does not when it is not viable or it breaks a rule of the world or of the player" : this.previewDue(state) ? "call preview_scene first: two or three sentences that show the player how the scene opens, before the characters are asked" : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : `nothing to ${attempted === "narrate" ? "deliver" : "resolve"} yet: call activate_characters first`;
3851
+ case "idle": return this.judgeDue(state) ? "call judge_action first: does what the player's character tries work? It does not when it is not viable or it breaks a rule of the world or of the player" : this.previewDue(state) ? "call preview_scene first: two or three sentences that show the player how the scene opens, before the characters are asked" : state.judgement?.allowed === false && attempted !== "activate_characters" ? `the attempt does not work (${state.judgement.reason}): call resolve_round with one outcome, for the player's character only (result failed, a sentence on what it does and why nothing comes of it)${attempted === "narrate" ? ", then narrate" : ""}` : attempted === "activate_characters" || attempted === void 0 ? "call activate_characters to let the characters act" : attempted === "narrate" ? "nothing to deliver yet: call activate_characters to let the characters act, or, when nobody else needs to react, call resolve_round with an outcome for the player's character alone, and then narrate" : "nothing to resolve yet: call activate_characters first";
3289
3852
  case "resolving": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round with one outcome for each of: ${waiting(state.first)}` : `call resolve_round with one outcome for each of: ${waiting(state.first)}`;
3290
3853
  case "retrying": return attempted === "activate_characters" ? "the characters already acted in this round: call resolve_round" : attempted === "narrate" ? `resolve the round first: call resolve_round once more, with one outcome for each of: ${waiting(state.second)}` : `call resolve_round once more, with one outcome for each of: ${waiting(state.second)}`;
3291
3854
  case "between": return attempted === "resolve_round" ? "the round is already recorded: call activate_characters again if the story needs it, or narrate" : `call narrate with the output of the turn${this.mustSay(state)}${this.canContinue(state)}`;
@@ -3357,6 +3920,7 @@ var TurnEngine = class {
3357
3920
  situation: state.situation,
3358
3921
  turn: owner.turn,
3359
3922
  policy: store.settings().memory,
3923
+ ...store.settings().diagnostics.keepRuns ? { explain: true } : {},
3360
3924
  ...queryVector === void 0 ? {} : { queryVector }
3361
3925
  }, store.story, signal) : state.recalled.get(key) ?? [];
3362
3926
  if (number === 1 && memories.length > 0) state.recalled.set(key, memories);
@@ -3374,6 +3938,7 @@ var TurnEngine = class {
3374
3938
  cast,
3375
3939
  situation: state.situation,
3376
3940
  attempt: number,
3941
+ language: store?.settings().prompts.language ?? "en",
3377
3942
  turn: owner.turn,
3378
3943
  ...away ? { away: true } : {},
3379
3944
  lookup: store?.settings().memory.lookup ?? false,
@@ -3411,10 +3976,13 @@ var TurnEngine = class {
3411
3976
  };
3412
3977
  } catch (error) {
3413
3978
  if (signal.aborted) throw error;
3979
+ const reason = error instanceof Error ? error.message : String(error);
3980
+ this.problem(`${member.character.name} could not act: ${reason}`);
3414
3981
  return {
3415
3982
  character: key,
3416
3983
  name: member.character.name,
3417
- reason: error instanceof Error ? error.message : String(error)
3984
+ reason,
3985
+ technical: true
3418
3986
  };
3419
3987
  }
3420
3988
  }));
@@ -3441,7 +4009,7 @@ var TurnEngine = class {
3441
4009
  if (!present.has(relation.toId) && !relevant.has(relation.toId)) return [];
3442
4010
  const other = cast.find((candidate) => candidate.character.id === relation.toId);
3443
4011
  return other === void 0 || other.key === member.key ? [] : [{
3444
- name: other.character.name,
4012
+ name: referent(other.character),
3445
4013
  label: relation.label,
3446
4014
  summary: relation.summary,
3447
4015
  present: present.has(relation.toId),
@@ -3741,7 +4309,7 @@ var TurnEngine = class {
3741
4309
  this.suggestAfter(owner, state, output);
3742
4310
  this.startDueWrite(owner, state);
3743
4311
  this.delivered.set(owner.chat, state);
3744
- this.consolidateIfDue(owner, state);
4312
+ this.afterTurn.start(owner, state.cancel.signal);
3745
4313
  if (run !== void 0) this.offSceneIfDue(owner, state, run);
3746
4314
  return output;
3747
4315
  }
@@ -4025,6 +4593,8 @@ function apply(ctx) {
4025
4593
  })), "roleplay: rerank memories");
4026
4594
  });
4027
4595
  ctx.effect(() => ctx.roleplayOrchestration.replace({ committer: recordKeeper({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: record keeper");
4596
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ judge: triggerJudge({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: trigger judge");
4597
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ strategist: factionStrategist({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: faction strategist");
4028
4598
  ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: world author");
4029
4599
  ctx.effect(() => ctx.roleplayOrchestration.replace({ suggester: suggestionWriter({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: suggestions");
4030
4600
  ctx.effect(() => ctx.roleplayState.bind((agentSessionId) => {