@dsh-agentic-roleplay/core 0.3.1 → 0.3.3

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 (39) hide show
  1. package/lib/authoring.js +13 -2
  2. package/lib/child-lPncV1ps.js +380 -0
  3. package/lib/client.js +1526 -356
  4. package/lib/client.js.map +1 -1
  5. package/lib/compaction.js +1 -1
  6. package/lib/deliver-De62a8i9.js +1929 -0
  7. package/lib/doctor-chat-ByDfCMeo.js +17 -0
  8. package/lib/doctor.js +95 -0
  9. package/lib/{documents-DtlY2IRt.js → documents-Do4lz4SB.js} +549 -64
  10. package/lib/{gallery-DACG5eh2.js → gallery-CtFDL22W.js} +2 -2
  11. package/lib/{generator-DGYcLMp7.js → generator-B6FxlKOV.js} +2 -378
  12. package/lib/hooks-Ka22sFNy.js +1019 -0
  13. package/lib/images.js +3 -3
  14. package/lib/index.js +303 -190
  15. package/lib/language-DWVwi1R7.js +520 -0
  16. package/lib/narration-DK2kiIjE.js +141 -0
  17. package/lib/orchestration.js +777 -2542
  18. package/lib/{packs-CkRZDCsV.js → packs-BYjrAen6.js} +4 -518
  19. package/lib/{presenter-agent-PK9JYExk.js → presenter-agent-Dt21K96b.js} +4 -3
  20. package/lib/{deliver-BDW5WZvc.js → reflection-md7BCYCl.js} +350 -769
  21. package/lib/{narration-5ig7Dg28.js → settings-CA6icLL_.js} +156 -141
  22. package/package.json +3 -2
  23. package/prompts/en/doctor/persona.md +1 -0
  24. package/prompts/en/doctor/procedure.md +5 -0
  25. package/prompts/en/doctor/welcome.md +1 -0
  26. package/prompts/en/import/character.md +1 -0
  27. package/prompts/en/roleplay/dice.md +7 -0
  28. package/prompts/en/roleplay/game-master.md +2 -0
  29. package/prompts/en/roleplay/reflection-check.md +5 -0
  30. package/prompts/en/roleplay/reflection.md +5 -1
  31. package/prompts/zh/doctor/persona.md +1 -0
  32. package/prompts/zh/doctor/procedure.md +5 -0
  33. package/prompts/zh/doctor/welcome.md +1 -0
  34. package/prompts/zh/import/character.md +1 -0
  35. package/prompts/zh/roleplay/dice.md +7 -0
  36. package/prompts/zh/roleplay/game-master.md +2 -0
  37. package/prompts/zh/roleplay/reflection-check.md +5 -0
  38. package/prompts/zh/roleplay/reflection.md +5 -1
  39. package/lib/src-CWTNeL6Y.js +0 -128
@@ -1,18 +1,44 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { B as shippedText, S as wrongLanguage, T as parsePlotsFile, W as ReflectionRefusedError, Y as INTENT_STATUSES, _ as API_PREFIX } from "./packs-CkRZDCsV.js";
3
- import { B as skipTime, D as observeSurroundings, E as observeAsPlayer, F as beginTurn, G as RESULTS, H as referent, I as describeTime, J as languageOf, K as answerEstimate, L as describeWhen, N as sameWords, P as ClockError, R as endRound, S as clearNotes, T as readNotes, U as AWAY_ACTION_SCHEMA, V as zoneOf, W as CHARACTER_ACTION_SCHEMA, Y as translator, _ as plotAuthorNeeded, b as updatePlotProgress, c as dueReflection, f as whereabouts, g as pacingAdvice, h as describePacingAdvice, i as keepRunDetail, k as Timelines, l as memoryReflector, m as addSessionPlot, q as parseCharacterAction, r as forgetRunDetails, s as recordActivity, t as deliverNow, u as recordFailure, w as putNote, x as addToNote, z as readTime } from "./deliver-BDW5WZvc.js";
4
- import { a as liveSettings, f as WORLD_RULES_KEY, n as encodeOutput, p as rulesOf, r as encodePreview } from "./narration-5ig7Dg28.js";
5
- import "./src-CWTNeL6Y.js";
6
- import { A as runChild, D as childSampling, E as childModel, M as tokensOf, T as uniqueKey, j as estimateAnswer, k as childTrace, o as addToLibrary, w as slug } from "./generator-DGYcLMp7.js";
7
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DACG5eh2.js";
8
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-PK9JYExk.js";
2
+ import { _ as API_PREFIX, y as INTENT_STATUSES } from "./packs-BYjrAen6.js";
3
+ import { a as whereabouts, d as sameWords, f as referent, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-md7BCYCl.js";
4
+ import "./settings-CA6icLL_.js";
5
+ import { D as ReflectionRefusedError, a as wrongLanguage } from "./language-DWVwi1R7.js";
6
+ import { A as ClockError, B as languageOf, L as zoneOf, N as describeWhen, R as RESULTS, S as toolEnabled, V as translator, b as MAX_OOC_ANSWER, c as externalGiven, d as PREVIEW_TOOL, f as createTools$1, y as AUTHORING_NEEDS } from "./deliver-De62a8i9.js";
7
+ import { a as liveSettings } from "./narration-DK2kiIjE.js";
8
+ import { a as runChild, i as childTrace, n as childSampling, o as estimateAnswer, s as tokensOf, t as childModel } from "./child-lPncV1ps.js";
9
+ import { T as uniqueKey, o as addToLibrary, w as slug } from "./generator-B6FxlKOV.js";
10
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CtFDL22W.js";
11
+ import { a as writeVerdicts, i as readVerdicts, n as installHooks, r as storesOf } from "./hooks-Ka22sFNy.js";
12
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Dt21K96b.js";
9
13
  import { join } from "node:path";
10
14
  import { existsSync } from "node:fs";
11
15
  import { SessionId } from "@deepseek-ai/dsh-session";
12
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
13
- import { defineTool } from "@deepseek-ai/dsh-tools";
14
16
  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, judgedStatements, lintWorld, localTime, locationKey, mentioned, nextOccurrence, occurrenceAt, parseInstant, parseRecordsEdit, planItemChange, planVariableChange, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
17
+ import { InvalidEditError, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, parseRecordsEdit, sessionDatabase, sessionFolder } from "@dsh-agentic-roleplay/state";
18
+ //#region src/host/tools/resource-hint.ts
19
+ /** The name DSH's MCP resource plugin gives the prompt paragraph it adds for every agent; a section of the same name in an agent's scope replaces it. */
20
+ const RESOURCE_HINT_SECTION = "mcp-resource-servers";
21
+ const RESOURCE_TOOLS = [
22
+ "list_mcp_resources",
23
+ "list_mcp_resource_templates",
24
+ "read_mcp_resource"
25
+ ];
26
+ const NAMESPACED = /^mcp__(.+?)__.+$/;
27
+ /**
28
+ * What an agent is told about MCP resources: nothing unless it can see a resource tool, since the plugin's own paragraph names the tools
29
+ * and servers to every agent whether or not it was given them, and an agent that is told of a tool it lacks goes looking for it. The servers are
30
+ * those with a tool registered for anyone, so that an agent given only the resource tools still learns their names.
31
+ */
32
+ function resourceHint(visible, registered, tr) {
33
+ const tools = RESOURCE_TOOLS.filter((name) => visible.includes(name));
34
+ if (tools.length === 0) return "";
35
+ const servers = [...new Set(registered.flatMap((name) => NAMESPACED.exec(name)?.[1] ?? []))].sort();
36
+ return servers.length === 0 ? tr("## MCP resource servers\n\nUse {tools} with the server argument naming an MCP server.", { tools: tools.join(", ") }) : tr("## MCP resource servers\n\nUse {tools} with one of these names as the server argument: {servers}.", {
37
+ tools: tools.join(", "),
38
+ servers: JSON.stringify(servers)
39
+ });
40
+ }
41
+ //#endregion
16
42
  //#region src/host/orchestration/committer.ts
17
43
  /** What the keeper reads back by default: the parts of the records its edits write. */
18
44
  const VERIFY_SECTIONS = [
@@ -34,11 +60,13 @@ function describeRound(round, known) {
34
60
  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}`,
35
61
  ...round.place === void 0 ? [] : [`Place of the moment: ${round.place.name} (${round.place.key})`],
36
62
  ...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)}` : ""}`],
63
+ ...round.rolls === void 0 ? [] : ["Dice rolled this round, which are facts (not interpreted by anyone):", ...round.rolls.map((line) => `- ${line}`)],
37
64
  "What each character did, and what became of it:",
38
65
  ...round.entries.map((entry) => [
39
66
  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
67
  entry.utterance === void 0 ? "" : ` said${entry.spoken ? "" : " (but was prevented from saying)"}: "${entry.utterance}"`,
41
68
  entry.publicState === void 0 ? "" : ` the game master says anyone present can now see: ${entry.publicState}`,
69
+ entry.rolled === void 0 ? "" : ` decided by the dice: ${entry.rolled}`,
42
70
  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("; ")}`,
43
71
  entry.items === void 0 ? "" : ` with things: ${entry.items.map((thing) => `${thing.name} (${thing.action}: ${thing.summary})`).join("; ")}`,
44
72
  entry.at === void 0 ? "" : ` was in ${entry.at.name} (${entry.at.key})${entry.moved === void 0 ? "" : ` and went to ${entry.moved.name} (${entry.moved.key})${entry.moved.position === void 0 ? "" : `, ${entry.moved.position}`}`}`
@@ -87,7 +115,7 @@ function describePrompt(job, memory) {
87
115
  ...records.open_threads.length === 0 ? ["- none"] : records.open_threads.map((thread) => `- id ${thread.id}: ${thread.text}`)
88
116
  ].join("\n");
89
117
  }
90
- const RESULT$4 = {
118
+ const RESULT$3 = {
91
119
  type: "object",
92
120
  properties: {
93
121
  complete: {
@@ -106,20 +134,23 @@ const RESULT$4 = {
106
134
  function keeperTools(job, memory, progress) {
107
135
  const turn = Math.max(...job.rounds.map((round) => round.turn));
108
136
  const keys = job.store.story.characters.list().map(characterKey);
137
+ const { tools } = job.store.settings();
109
138
  const wanted = /* @__PURE__ */ new Set([
110
139
  "read_records",
111
140
  "edit_records",
112
- "search_events",
113
- "list_threads",
114
141
  "list_locations",
115
142
  "get_location",
116
143
  "list_factions",
117
144
  "get_faction",
118
- "list_relationships",
119
- "list_items",
120
145
  "get_item",
121
146
  "get_agenda",
122
- "list_variables"
147
+ "list_variables",
148
+ ...[
149
+ "search_events",
150
+ "list_threads",
151
+ "list_relationships",
152
+ "list_items"
153
+ ].filter((name) => toolEnabled(tools, "records", name))
123
154
  ]);
124
155
  return createTools(() => ({
125
156
  session: job.store.story,
@@ -205,7 +236,8 @@ function recordKeeper(deps) {
205
236
  persona: promptFor(parent, "roleplay/record-keeper", job.store.settings().prompts.language),
206
237
  prompt: describePrompt(job, memory),
207
238
  tools: keeperTools(job, memory, progress),
208
- result: RESULT$4,
239
+ external: externalGiven(parent.ctx.tools, job.store.settings().tools, "records"),
240
+ result: RESULT$3,
209
241
  beforeSubmit: () => {
210
242
  if (progress.edits === 0 && !warned) {
211
243
  warned = true;
@@ -234,7 +266,7 @@ function suggestionProblems(lines, wanted) {
234
266
  const tidySuggestions = (lines) => lines.map((line) => line.trim().replace(/\s+/g, " "));
235
267
  //#endregion
236
268
  //#region src/host/orchestration/suggester.ts
237
- const RESULT$3 = {
269
+ const RESULT$2 = {
238
270
  type: "object",
239
271
  properties: { options: {
240
272
  type: "array",
@@ -273,7 +305,7 @@ function suggestionWriter(deps) {
273
305
  trace: childTrace(job.store, "suggestions", "suggestions"),
274
306
  persona: promptFor(parent, "roleplay/suggester", job.store.settings().prompts.language, { max: 200 }),
275
307
  prompt: promptOf(job),
276
- result: RESULT$3,
308
+ result: RESULT$2,
277
309
  beforeSubmit: (value) => {
278
310
  const problems = suggestionProblems(tidySuggestions(value.options), job.count);
279
311
  return problems.length === 0 ? void 0 : `not acceptable: ${problems.join("; ")}`;
@@ -283,33 +315,8 @@ function suggestionWriter(deps) {
283
315
  } };
284
316
  }
285
317
  //#endregion
286
- //#region src/host/triggers/judged.ts
287
- const KEY = "triggers.judged";
288
- function readVerdicts(session) {
289
- const stored = session.metadata.getValue(KEY);
290
- if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
291
- const verdicts = {};
292
- for (const [statement, value] of Object.entries(stored)) {
293
- const verdict = value;
294
- if (typeof verdict === "object" && verdict !== null && typeof verdict.holds === "boolean" && typeof verdict.turn === "number") verdicts[statement] = {
295
- holds: verdict.holds,
296
- turn: verdict.turn
297
- };
298
- }
299
- return verdicts;
300
- }
301
- /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
302
- function writeVerdicts(session, verdicts, keep) {
303
- session.metadata.setValue(KEY, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
304
- }
305
- /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
306
- const verdictReader = (session) => {
307
- const verdicts = readVerdicts(session);
308
- return (statement) => verdicts[statement]?.holds === true;
309
- };
310
- //#endregion
311
318
  //#region src/host/triggers/judge.ts
312
- const RESULT$2 = {
319
+ const RESULT$1 = {
313
320
  type: "object",
314
321
  properties: { verdicts: {
315
322
  type: "array",
@@ -376,7 +383,7 @@ function triggerJudge(deps) {
376
383
  trace: childTrace(store, "records", "trigger judge"),
377
384
  persona: promptFor(parent, "roleplay/trigger-judge", store.settings().prompts.language),
378
385
  prompt: brief$1(job, statements),
379
- result: RESULT$2,
386
+ result: RESULT$1,
380
387
  beforeSubmit: (value) => {
381
388
  const numbers = value.verdicts.map((verdict) => verdict.number);
382
389
  const missing = statements.flatMap((_, index) => numbers.includes(index + 1) ? [] : [index + 1]);
@@ -414,7 +421,7 @@ const DECISION_LIMITS = [
414
421
  ...Array.from({ length: 6 }, () => 200),
415
422
  ...Array.from({ length: MAX_ACTIVE_GOALS }, () => 10)
416
423
  ];
417
- const keyOf$1 = (faction) => faction.sourceId ?? String(faction.id);
424
+ const keyOf = (faction) => faction.sourceId ?? String(faction.id);
418
425
  function lastActed(session) {
419
426
  const stored = session.metadata.getValue(LAST_KEY);
420
427
  return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
@@ -427,7 +434,7 @@ function dueFactions(session, now, everyDays) {
427
434
  const last = lastActed(session);
428
435
  const due = [];
429
436
  for (const faction of session.factions.list()) {
430
- const key = keyOf$1(faction);
437
+ const key = keyOf(faction);
431
438
  if (last[key] === void 0) {
432
439
  last[key] = now;
433
440
  continue;
@@ -445,10 +452,10 @@ function dueFactions(session, now, everyDays) {
445
452
  function markActed(session, faction, now) {
446
453
  session.metadata.setValue(LAST_KEY, {
447
454
  ...lastActed(session),
448
- [keyOf$1(faction)]: now
455
+ [keyOf(faction)]: now
449
456
  });
450
457
  }
451
- const RESULT$1 = {
458
+ const RESULT = {
452
459
  type: "object",
453
460
  properties: {
454
461
  summary: {
@@ -590,8 +597,8 @@ function factionStrategist(deps) {
590
597
  ...childModel(store.settings(), "authoring"),
591
598
  trace: childTrace(store, "authoring", `faction ${faction.name}`),
592
599
  persona: promptFor(parent, "roleplay/faction-strategist", store.settings().prompts.language),
593
- prompt: brief(session, faction, now, zone, last[keyOf$1(faction)] ?? now),
594
- result: RESULT$1,
600
+ prompt: brief(session, faction, now, zone, last[keyOf(faction)] ?? now),
601
+ result: RESULT,
595
602
  maxCalls: 3
596
603
  });
597
604
  applyStrategy(job, session, faction, strategy, now);
@@ -925,917 +932,30 @@ function worldAuthor(deps) {
925
932
  };
926
933
  }
927
934
  //#endregion
928
- //#region src/host/triggers/notes.ts
929
- /** Fires the triggers whose conditions just came true, and says what each did in words. A trigger that could not be applied is reported and given up. */
930
- function fireTriggers(session, input) {
931
- const { settings, turn, round, now, zone, problem } = input;
932
- if (!settings.triggers.enabled) return { fired: [] };
933
- const before = Math.max(0, ...session.triggers.notes().map((note) => note.id));
934
- const run = session.runTriggers({
935
- turn,
936
- round,
937
- now,
938
- zone,
939
- maxFires: settings.triggers.maxFires,
940
- judged: verdictReader(session)
941
- });
942
- for (const failure of run.failed) problem(`the trigger "${failure.trigger.key}" could not fire and is given up: ${failure.problem}`);
943
- const names = new Map(session.characters.list().map((character) => [character.id, character.name]));
944
- const fresh = session.triggers.notes({ status: "pending" }).filter((note) => note.id > before);
945
- const told = new Map(deliverNow(session, fresh, {
946
- now,
947
- zone
948
- }).map((entry) => [entry.id, entry.text]));
949
- return { fired: run.fired.map((fired) => ({
950
- name: fired.trigger.name,
951
- events: fired.events,
952
- cues: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "cue" && told.has(note.id)).map((note) => ({
953
- names: note.characterIds.flatMap((id) => names.get(id) ?? []),
954
- text: told.get(note.id)
955
- })),
956
- beats: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "beat" && told.has(note.id)).map((note) => ({
957
- id: note.id,
958
- text: told.get(note.id)
959
- }))
960
- })) };
961
- }
962
- /** When something is to happen, as it is told: the date and how far off it is. */
963
- function whenText(at, clock) {
964
- if (at === void 0) return void 0;
965
- return `${describeInstant(at, clock.zone)}${at > clock.now ? `, in ${describeDuration(at - clock.now)}` : ""}`;
966
- }
967
- function whoKnows(session, announcement) {
968
- const { audience } = announcement;
969
- if (audience === "everyone") return "everyone";
970
- if ("place" in audience) return `whoever is at ${session.locations.list().find((place) => locationKey(place) === audience.place)?.name ?? audience.place}`;
971
- return audience.characters.map((key) => session.characters.list().find((entry) => (entry.sourceId ?? String(entry.id)) === key)?.name ?? key).join(", ");
972
- }
973
- /** At most this many announcements are told to one character at once: soonest first. */
974
- const MAX_UPCOMING_FOR_CHARACTER = 3;
975
- /** The beats still to weave in, the cues of a character, and what is done with them. Each is written from the story as it stands when it is told, and one that no longer applies is withdrawn. */
976
- function noteStore(session, settings, clock) {
977
- return {
978
- upcoming: (turn) => {
979
- const now = clock(turn);
980
- return announcements(session, now).map((entry) => {
981
- const when = whenText(entry.at, now);
982
- return {
983
- text: entry.text,
984
- who: whoKnows(session, entry),
985
- ...when === void 0 ? {} : { when }
986
- };
987
- });
988
- },
989
- upcomingFor: (characterId, turn) => {
990
- const now = clock(turn);
991
- return announcements(session, now).filter((entry) => inAudience(session, entry.audience, characterId)).slice(0, MAX_UPCOMING_FOR_CHARACTER).map((entry) => {
992
- const when = whenText(entry.at, now);
993
- return {
994
- text: entry.text,
995
- ...when === void 0 ? {} : { when }
996
- };
997
- });
998
- },
999
- pendingBeats: () => deliverNow(session, session.triggers.notes({
1000
- status: "pending",
1001
- kind: "beat"
1002
- }), clock(session.metadata.get().turns + 1)),
1003
- resolveBeats: (ids) => {
1004
- const pending = new Set(session.triggers.notes({
1005
- status: "pending",
1006
- kind: "beat"
1007
- }).map((note) => note.id));
1008
- const unknown = ids.filter((id) => !pending.has(id));
1009
- if (unknown.length > 0) throw new Error(`${unknown.join(", ")} ${unknown.length === 1 ? "is" : "are"} not ${unknown.length === 1 ? "a beat" : "beats"} still to weave in`);
1010
- session.transaction(() => {
1011
- for (const id of ids) session.triggers.resolveNote(id, "done");
1012
- });
1013
- },
1014
- cuesFor: (characterId) => deliverNow(session, session.triggers.notes({
1015
- status: "pending",
1016
- kind: "cue"
1017
- }).filter((note) => note.characterIds.includes(characterId)), clock(session.metadata.get().turns + 1)),
1018
- doneCues: (ids) => {
1019
- session.transaction(() => {
1020
- for (const id of ids) session.triggers.resolveNote(id, "done");
1021
- });
1022
- },
1023
- lapseNotes: (turn) => {
1024
- const { triggers } = settings();
1025
- session.lapseNotes(turn, {
1026
- beats: triggers.beatTurns,
1027
- cues: triggers.cueTurns
1028
- });
1029
- }
1030
- };
1031
- }
1032
- //#endregion
1033
- //#region src/host/clock/agenda.ts
1034
- const CURSOR = "agenda.cursor";
1035
- const ASKED = "agenda.asked";
1036
- /** At most this many characters are asked to be given a day at a time, so that it never floods the world author. */
1037
- const MAX_ASKED = 3;
1038
- /** How far ahead the characters are told about what comes next in their day. */
1039
- const NEXT_HORIZON = 240 * MINUTE;
1040
- /** What a character is shown of its own agenda at most. */
1041
- const SHOWN_ENGAGEMENTS = 4;
1042
- const SHOWN_GOALS = 3;
1043
- const keyOfCharacter$1 = (character) => character.sourceId ?? String(character.id);
1044
- /**
1045
- * Bring the days of the characters up to the story's time: those who are not in the player's scene go where their
1046
- * routine has them now, and take up what it has them doing, when the window they are in has changed since the last
1047
- * time. Characters in the scene stay: the game master is told what their day expects of them instead. It costs
1048
- * nothing but a look at each character's windows, however long the story was skipped.
1049
- */
1050
- function catchUpRoutines(session, zone, now, turn, ask) {
1051
- return session.transaction(() => {
1052
- const cursor = typeof session.metadata.getValue(CURSOR) === "number" ? session.metadata.getValue(CURSOR) : void 0;
1053
- if (cursor === now) return [];
1054
- const player = session.characters.list().find((character) => character.control === "player");
1055
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1056
- const moves = [];
1057
- const alreadyAsked = new Set(Array.isArray(session.metadata.getValue(ASKED)) ? session.metadata.getValue(ASKED) : []);
1058
- const asked = [];
1059
- for (const character of session.characters.list()) {
1060
- if (character.control === "player") continue;
1061
- const characterId = character.id;
1062
- const window = session.routines.list(characterId);
1063
- const here = session.placements.get("character", characterId);
1064
- const away = playerPlace === void 0 || here?.locationId !== playerPlace;
1065
- if (window.length === 0) {
1066
- if (ask && playerPlace !== void 0 && away && cursor !== void 0 && asked.length < MAX_ASKED && character.kind === "person" && character.tier !== "background" && !alreadyAsked.has(characterId)) {
1067
- session.consolidation.enqueue({
1068
- kind: "character",
1069
- subjectId: characterId,
1070
- note: "has no routine: give it a day (routines), as far as its role and the story imply",
1071
- turn
1072
- });
1073
- asked.push(characterId);
1074
- }
1075
- continue;
1076
- }
1077
- if (!away) continue;
1078
- const current = occurrenceAt(window, now, zone);
1079
- if (current === void 0) continue;
1080
- const before = cursor === void 0 ? void 0 : occurrenceAt(window, cursor, zone);
1081
- if (before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
1082
- const target = current.window;
1083
- if (target.locationId !== void 0 && (here?.locationId !== target.locationId || target.position !== void 0 && here.position !== target.position)) {
1084
- session.move(characterId, {
1085
- to: target.locationId,
1086
- ignoreExits: true,
1087
- ...target.position === void 0 ? {} : { position: target.position },
1088
- ...target.featureKey === void 0 ? {} : { featureKey: target.featureKey }
1089
- });
1090
- moves.push({
1091
- character: keyOfCharacter$1(character),
1092
- name: character.name,
1093
- to: session.locations.get(target.locationId)?.name ?? String(target.locationId),
1094
- activity: target.activity
1095
- });
1096
- }
1097
- if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
1098
- }
1099
- session.metadata.setValue(CURSOR, now);
1100
- if (asked.length > 0) session.metadata.setValue(ASKED, [...alreadyAsked, ...asked]);
1101
- return moves;
1102
- });
1103
- }
1104
- /** A character's agenda at an instant, with places by name and others by name. */
1105
- function agendaView(session, characterId, zone, now) {
1106
- const agenda = agendaAt(session, characterId, now, zone, {
1107
- horizon: NEXT_HORIZON,
1108
- engagements: SHOWN_ENGAGEMENTS,
1109
- goals: SHOWN_GOALS
1110
- });
1111
- const place = (id) => id === void 0 ? void 0 : session.locations.get(id)?.name;
1112
- const names = (ids) => ids.filter((id) => id !== characterId).map((id) => session.characters.get(id)?.name ?? String(id));
1113
- return {
1114
- zone,
1115
- ...agenda.now === void 0 ? {} : { now: {
1116
- activity: agenda.now.window.activity,
1117
- ...place(agenda.now.window.locationId) === void 0 ? {} : { place: place(agenda.now.window.locationId) },
1118
- until: agenda.now.endsAt,
1119
- interruptible: agenda.now.window.interruptible
1120
- } },
1121
- ...agenda.next === void 0 ? {} : { next: {
1122
- activity: agenda.next.window.activity,
1123
- ...place(agenda.next.window.locationId) === void 0 ? {} : { place: place(agenda.next.window.locationId) },
1124
- at: agenda.next.startsAt
1125
- } },
1126
- engagements: agenda.engagements.map(({ engagement, overdue }) => ({
1127
- title: engagement.title,
1128
- at: engagement.at,
1129
- ...place(engagement.locationId) === void 0 ? {} : { place: place(engagement.locationId) },
1130
- with: names(engagement.participants),
1131
- overdue
1132
- })),
1133
- goals: agenda.goals.map(({ intent, deadlineAt, overdue }) => ({
1134
- name: intent.name,
1135
- type: intent.type,
1136
- description: intent.description,
1137
- plan: intent.plan.slice(0, 3),
1138
- ...deadlineAt === void 0 ? {} : { deadline: deadlineAt },
1139
- overdue
1140
- }))
1141
- };
1142
- }
1143
- /** How soon ahead the game master is told of a window ending or a commitment falling due. */
1144
- const SOON = 30 * MINUTE;
1145
- const MAX_NOTES = 6;
1146
- /** An engagement that has been overdue for longer than this is not worth the game master's attention every turn. */
1147
- const STALE = 1440 * MINUTE;
1148
- function sceneAgenda(session, zone, now, moved) {
1149
- const player = session.characters.list().find((character) => character.control === "player");
1150
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1151
- const withPlayer = new Set(session.characters.list().filter((character) => playerPlace !== void 0 && session.placements.get("character", character.id)?.locationId === playerPlace && character.control !== "player").map((character) => character.id));
1152
- const here = [];
1153
- for (const characterId of withPlayer) {
1154
- const windows = session.routines.list(characterId);
1155
- const current = occurrenceAt(windows, now, zone);
1156
- const upcoming = nextOccurrence(windows, now, zone, SOON);
1157
- const name = session.characters.get(characterId)?.name ?? String(characterId);
1158
- const place = current?.window.locationId === void 0 ? void 0 : session.locations.get(current.window.locationId);
1159
- if (current !== void 0 && current.window.locationId !== void 0 && current.window.locationId !== playerPlace) here.push({
1160
- name,
1161
- note: `its day says "${current.window.activity}"${place === void 0 ? "" : ` at ${place.name}`} now, yet it is here`
1162
- });
1163
- else if (current !== void 0 && current.endsAt - now <= SOON) here.push({
1164
- name,
1165
- note: `"${current.window.activity}" is due to end soon`
1166
- });
1167
- else if (current === void 0 && upcoming !== void 0) here.push({
1168
- name,
1169
- note: `"${upcoming.window.activity}" begins soon${upcoming.window.locationId === void 0 ? "" : ` at ${session.locations.get(upcoming.window.locationId)?.name ?? ""}`}`
1170
- });
1171
- }
1172
- const engagements = session.engagements.list({
1173
- status: "pending",
1174
- to: now + SOON
1175
- }).filter((engagement) => now - (engagement.until ?? engagement.at) < STALE).slice(0, MAX_NOTES).map((engagement) => ({
1176
- title: engagement.title,
1177
- at: engagement.at,
1178
- ...engagement.locationId === void 0 ? {} : { place: session.locations.get(engagement.locationId)?.name ?? "" },
1179
- with: engagement.participants.map((id) => session.characters.get(id)?.name ?? String(id)),
1180
- overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE)
1181
- }));
1182
- return {
1183
- zone,
1184
- moved,
1185
- here: here.slice(0, MAX_NOTES),
1186
- engagements
1187
- };
1188
- }
1189
- //#endregion
1190
- //#region src/host/clock/passage.ts
1191
- /** The start of a turn: the time, how long the player was away, and what the days of the characters make of it. */
1192
- function startTurn(session, config, turn, wall) {
1193
- const started = beginTurn(session, config, turn, wall);
1194
- const moved = catchUpRoutines(session, started.time.zone, started.time.now, turn, true);
1195
- return {
1196
- ...started,
1197
- agenda: sceneAgenda(session, started.time.zone, started.time.now, moved)
1198
- };
1199
- }
1200
- /** A round passes, and the characters outside the scene take up what their days have for the new time. */
1201
- function passRound(session, config, turn, round, wall, stated, minimum) {
1202
- const span = endRound(session, config, turn, round, wall, stated, minimum);
1203
- return {
1204
- ...span,
1205
- moved: catchUpRoutines(session, span.zone, span.to, turn, false)
1206
- };
1207
- }
1208
- /** Time is skipped, and the characters outside the scene take up what their days have for the new time. */
1209
- function skipAhead(session, config, turn, round, wall, request) {
1210
- const span = skipTime(session, config, turn, round, wall, request);
1211
- return {
1212
- ...span,
1213
- moved: catchUpRoutines(session, span.zone, span.to, turn, true)
1214
- };
1215
- }
1216
- /** What a character is told of its own agenda. */
1217
- function agendaFor(session, config, turn, wall, characterId) {
1218
- const time = readTime(session, config, turn, wall());
1219
- return agendaView(session, characterId, zoneOf(config), time.now);
1220
- }
1221
- //#endregion
1222
- //#region src/host/clock/offscene.ts
1223
- const HANDLED = "offscene.handled";
1224
- const keyOf = (character) => character.sourceId ?? String(character.id);
1225
- function handledKeys(session) {
1226
- const stored = session.metadata.getValue(HANDLED);
1227
- return new Set(Array.isArray(stored) ? stored.filter((entry) => typeof entry === "string") : []);
1228
- }
1229
- /** Remember that these were dealt with, so that they are not dealt with again. */
1230
- function markHandled(session, keys) {
1231
- session.metadata.setValue(HANDLED, [...handledKeys(session), ...keys].slice(-500));
1232
- }
1233
- /**
1234
- * What has fallen due for characters who are not with the player and who have not dealt with it yet: commitments
1235
- * whose time has come with everyone to do with them away from the scene, and goals whose deadline has passed.
1236
- * Oldest first.
1237
- */
1238
- function dueOffScene(session, zone, now, language = "en") {
1239
- const tr = translator(language);
1240
- const when = (instant) => describeWhen(instant, now, zone, language);
1241
- const handled = handledKeys(session);
1242
- const characters = session.characters.list();
1243
- const player = characters.find((character) => character.control === "player");
1244
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1245
- const away = (id) => playerPlace !== void 0 && session.placements.get("character", id)?.locationId !== playerPlace;
1246
- const agents = new Map(characters.filter((character) => character.control === "agent").map((character) => [character.id, character]));
1247
- const items = [];
1248
- for (const engagement of session.engagements.list({
1249
- status: "pending",
1250
- to: now + 1
1251
- })) {
1252
- const key = `e${engagement.id}`;
1253
- if (handled.has(key) || now < engagement.at + 1) continue;
1254
- const everyone = engagement.participants;
1255
- if (everyone.some((id) => !agents.has(id) || !away(id))) continue;
1256
- const place = engagement.locationId === void 0 ? void 0 : session.locations.get(engagement.locationId);
1257
- items.push({
1258
- key,
1259
- kind: "engagement",
1260
- at: engagement.at,
1261
- characters: everyone.map((id) => keyOf(agents.get(id))),
1262
- ...place === void 0 ? {} : { place: place.sourceId ?? String(place.id) },
1263
- text: [
1264
- `${place === void 0 ? tr("You were to {title}, at {when}", {
1265
- title: engagement.title,
1266
- when: when(engagement.at)
1267
- }) : tr("You were to {title} at {place}, at {when}", {
1268
- title: engagement.title,
1269
- place: place.name,
1270
- when: when(engagement.at)
1271
- })}${engagement.note === "" ? "" : tr(" ({note})", { note: engagement.note })}${tr(".")}`,
1272
- now > engagement.at + ENGAGEMENT_GRACE ? tr("It is {now} now and the time has passed.", { now: when(now) }) : tr("It is {now} now.", { now: when(now) }),
1273
- tr("It was with: {who}.", { who: everyone.map((id) => agents.get(id).name).join(tr(", ")) }),
1274
- tr("You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.")
1275
- ].join(" ")
1276
- });
1277
- }
1278
- for (const character of agents.values()) {
1279
- if (!away(character.id)) continue;
1280
- for (const goal of session.intents.list(character.id, { status: "active" })) {
1281
- const key = `g${goal.id}`;
1282
- let deadline;
1283
- try {
1284
- deadline = goal.deadline === void 0 ? void 0 : parseInstant(goal.deadline, zone);
1285
- } catch {
1286
- deadline = void 0;
1287
- }
1288
- if (handled.has(key) || deadline === void 0 || deadline >= now) continue;
1289
- items.push({
1290
- key,
1291
- kind: "goal",
1292
- at: deadline,
1293
- characters: [keyOf(character)],
1294
- text: `${tr("The time you had for \"{goal}\" has passed ({when}; it is {now} now)", {
1295
- goal: goal.name,
1296
- when: when(deadline),
1297
- now: when(now)
1298
- })}${goal.description === "" ? "" : `${tr(": ")}${goal.description}`} ${tr("You are not with the player's character and nothing of this happens in front of anyone: decide what you do about it.")}`
1299
- });
1300
- }
1301
- }
1302
- return items.sort((a, b) => a.at - b.at);
1303
- }
1304
- //#endregion
1305
- //#region src/host/variables/describe.ts
1306
- /** What is tracked of a subject, in a line: `Health: hurt (2); Valence: unhappy (-0.4), usually even (0)`. */
1307
- function describeShown(shown) {
1308
- return shown.map(({ variable, value, baseline }) => {
1309
- const usual = baseline !== void 0 && baseline !== value ? `, usually ${describeValue(variable, baseline)}` : "";
1310
- return `${variable.name}: ${describeValue(variable, value)}${usual}`;
1311
- }).join("; ");
1312
- }
1313
- //#endregion
1314
- //#region src/host/orchestration/store.ts
1315
- /** The rules the session copied from its world when it started. */
1316
- function worldRules(session) {
1317
- const value = session.metadata.getValue(WORLD_RULES_KEY);
1318
- return Array.isArray(value) ? value.filter((rule) => typeof rule === "string") : [];
1319
- }
1320
- const keyOfCharacter = (character) => character.sourceId ?? String(character.id);
1321
- function placeOf(session, characterId) {
1322
- const placement = session.placements.get("character", characterId);
1323
- const location = placement === void 0 ? void 0 : session.locations.get(placement.locationId);
1324
- if (placement === void 0 || location === void 0) return void 0;
1325
- const feature = placement.featureKey === void 0 ? void 0 : location.features.find((candidate) => candidate.key === placement.featureKey);
1326
- return {
1327
- location,
1328
- position: placement.position,
1329
- ...feature === void 0 ? {} : { feature }
1330
- };
1331
- }
1332
- function castOf(session) {
1333
- return session.characters.list().map((character) => {
1334
- const state = session.characterStates.get(character.id);
1335
- const place = placeOf(session, character.id);
1336
- return {
1337
- key: keyOfCharacter(character),
1338
- character,
1339
- ...state === void 0 ? {} : { state },
1340
- ...place === void 0 ? {} : { place }
1341
- };
1342
- });
1343
- }
1344
- /** How much of what is in a container is told: a bag with fifty things in it is not recited. */
1345
- const SHOWN_CONTENTS = 5;
1346
- function viewOf(session, id, where) {
1347
- const item = session.items.get(id);
1348
- if (item === void 0) return void 0;
1349
- const inside = item.container?.state === "open" ? session.items.contents({
1350
- kind: "item",
1351
- id
1352
- }).filter((entry) => !entry.item.hidden).map((entry) => entry.item.quantity > 1 ? `${entry.item.quantity} ${entry.item.name}` : entry.item.name) : void 0;
1353
- return {
1354
- key: itemKey(item),
1355
- name: item.name,
1356
- quantity: item.quantity,
1357
- quality: item.quality,
1358
- notable: item.notable,
1359
- hidden: item.hidden,
1360
- ...item.container === void 0 ? {} : { state: item.container.state },
1361
- ...inside === void 0 || inside.length === 0 ? {} : { contents: [...inside.slice(0, SHOWN_CONTENTS), ...inside.length > SHOWN_CONTENTS ? [`and ${inside.length - SHOWN_CONTENTS} more`] : []] },
1362
- ...where === void 0 || where === "" ? {} : { where }
1363
- };
1364
- }
1365
- /** What lies in a place, notable things first; hidden things are included only when asked for. */
1366
- function itemsIn(session, locationId, withHidden) {
1367
- return session.items.contents({
1368
- kind: "location",
1369
- id: locationId
1370
- }).filter((entry) => withHidden || !entry.item.hidden).sort((a, b) => Number(b.item.notable) - Number(a.item.notable) || a.item.id - b.item.id).flatMap((entry) => {
1371
- const holder = entry.holding.holder;
1372
- const feature = holder.kind === "location" && holder.featureKey !== void 0 ? session.locations.get(locationId)?.features.find((candidate) => candidate.key === holder.featureKey)?.name : void 0;
1373
- const where = holder.kind === "location" ? [holder.position, feature === void 0 ? void 0 : `at ${feature}`].filter((part) => part !== void 0 && part !== "").join(", ") : "";
1374
- const view = viewOf(session, entry.item.id, where);
1375
- return view === void 0 ? [] : [view];
1376
- });
1377
- }
1378
- function carriedBy(session, characterId) {
1379
- return session.items.contents({
1380
- kind: "character",
1381
- id: characterId
1382
- }).sort((a, b) => Number(b.item.notable) - Number(a.item.notable) || a.item.id - b.item.id).flatMap((entry) => {
1383
- const holder = entry.holding.holder;
1384
- const view = viewOf(session, entry.item.id, holder.kind === "character" && holder.mode === "worn" ? `worn on the ${holder.slot}` : "carried");
1385
- return view === void 0 ? [] : [view];
1386
- });
1387
- }
1388
- function knowledgeOf(session, characterId, turn, visibleCharacters) {
1389
- observeSurroundings(session, characterId, turn);
1390
- const placement = session.placements.get("character", characterId);
1391
- 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);
1392
- const locations = session.knowledge.list(characterId, "location").flatMap((entry) => {
1393
- const place = session.locations.get(entry.subjectId);
1394
- return place === void 0 ? [] : [place.name];
1395
- });
1396
- const items = session.knowledge.list(characterId, "item").flatMap((entry) => {
1397
- const item = session.items.get(entry.subjectId);
1398
- return item === void 0 ? [] : [item.name];
1399
- });
1400
- const allExits = session.locations.allExits();
1401
- const routes = session.knowledge.list(characterId, "exit").flatMap((entry) => {
1402
- const exit = allExits.find((candidate) => candidate.id === entry.subjectId);
1403
- const from = exit === void 0 ? void 0 : session.locations.get(exit.fromId);
1404
- const to = exit === void 0 ? void 0 : session.locations.get(exit.toId);
1405
- return from === void 0 || to === void 0 ? [] : [`${from.name} -> ${to.name}`];
1406
- });
1407
- return {
1408
- characters: session.relationships.from(characterId).flatMap((relation) => {
1409
- const character = session.characters.get(relation.toId);
1410
- return character === void 0 ? [] : [character.name];
1411
- }),
1412
- factions: session.factionRelationships.from("character", characterId).filter((relation) => relation.toKind === "faction").flatMap((relation) => {
1413
- const faction = session.factions.get(relation.toId);
1414
- return faction === void 0 ? [] : [faction.name];
1415
- }),
1416
- locations,
1417
- items,
1418
- routes
1419
- };
1420
- }
1421
- function affiliationsOf(session, characterId) {
1422
- return session.factionMemberships.ofCharacter(characterId).flatMap((membership) => {
1423
- const faction = session.factions.get(membership.factionId);
1424
- if (faction === void 0) return [];
1425
- const relation = session.factionRelationships.get("character", characterId, "faction", faction.id);
1426
- const relationship = relation === void 0 ? void 0 : {
1427
- name: faction.name,
1428
- label: relation.label,
1429
- summary: relation.summary,
1430
- present: false,
1431
- familiarity: relation.familiarity,
1432
- trust: relation.trust,
1433
- affinity: relation.affinity,
1434
- tension: relation.tension
1435
- };
1436
- return [{
1437
- name: faction.name,
1438
- role: membership.role,
1439
- rank: membership.rank,
1440
- status: membership.status,
1441
- commitment: membership.commitment,
1442
- publicState: session.factionStates.get(faction.id)?.publicState ?? "",
1443
- goals: session.factionIntents.list(faction.id, { status: "active" }).map((intent) => intent.name),
1444
- ...relationship === void 0 ? {} : { relationship }
1445
- }];
1446
- });
1447
- }
1448
- function placeViewOf(session, locationId) {
1449
- const location = session.locations.get(locationId);
1450
- if (location === void 0) return void 0;
1451
- const here = new Set(session.placements.at(locationId, "character").map((placement) => placement.entityId));
1452
- return {
1453
- key: locationKey(location),
1454
- location,
1455
- exits: session.locations.exitsFrom(locationId).flatMap((exit) => {
1456
- const to = session.locations.get(exit.toId);
1457
- return to === void 0 ? [] : [{
1458
- key: locationKey(to),
1459
- name: to.name,
1460
- exit
1461
- }];
1462
- }),
1463
- here: castOf(session).filter((member) => here.has(member.character.id)),
1464
- items: itemsIn(session, locationId, false)
1465
- };
1466
- }
1467
- var DryRunDone = class extends Error {};
1468
- /** Do the changes in order inside a transaction that is always undone, so that a later change sees the earlier ones. */
1469
- function dryRunItems(session, entries) {
1470
- const problems = [];
1471
- const effects = [];
1472
- try {
1473
- session.transaction(() => {
1474
- for (const entry of entries) {
1475
- const character = session.characters.list().find((candidate) => keyOfCharacter(candidate) === entry.character);
1476
- const mine = [];
1477
- effects.push(mine);
1478
- if (character === void 0) {
1479
- problems.push(`${entry.character}: there is no such character`);
1480
- continue;
1481
- }
1482
- for (const spec of entry.changes) {
1483
- const planned = planItemChange(session, character.id, spec);
1484
- if (!planned.ok) {
1485
- problems.push(...planned.problems.map((problem) => `${entry.character}: cannot ${spec.action} ${spec.item}: ${problem}`));
1486
- break;
1487
- }
1488
- mine.push(applyItemPlan(session, planned.plan));
1489
- }
1490
- }
1491
- throw new DryRunDone();
1492
- });
1493
- } catch (error) {
1494
- if (!(error instanceof DryRunDone)) throw error;
1495
- }
1496
- return problems.length === 0 ? {
1497
- ok: true,
1498
- effects
1499
- } : {
1500
- ok: false,
1501
- problems
1502
- };
1503
- }
1504
- /** What a character can tell of itself and of those with it, in words. */
1505
- function trackedFor(session, characterId, presentIds) {
1506
- const character = session.characters.get(characterId);
1507
- return {
1508
- self: character === void 0 ? "" : describeShown(shownVariables(session, "character", characterId, keyOfCharacter(character), "self")),
1509
- others: presentIds.filter((id) => id !== characterId).flatMap((id) => {
1510
- const other = session.characters.get(id);
1511
- const text = other === void 0 ? "" : describeShown(shownVariables(session, "character", id, keyOfCharacter(other), "others"));
1512
- return other === void 0 || text === "" ? [] : [{
1513
- name: other.name,
1514
- text
1515
- }];
1516
- })
1517
- };
1518
- }
1519
- /** At most this many lines of what the story tracks are told to the game master at once. */
1520
- const MAX_TRACKED_LINES = 14;
1521
- /** What the story tracks, for the game master: everything, the scene first. */
1522
- function trackedLines(session) {
1523
- const player = session.characters.list().find((character) => character.control === "player");
1524
- const here = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1525
- const near = (characterId) => here !== void 0 && session.placements.get("character", characterId)?.locationId === here ? 0 : 1;
1526
- const lines = [];
1527
- const world = describeShown(shownVariables(session, "world", 0, "world", "story"));
1528
- if (world !== "") lines.push(`the world: ${world}`);
1529
- if (here !== void 0) {
1530
- const place = session.locations.get(here);
1531
- const text = place === void 0 ? "" : describeShown(shownVariables(session, "location", here, locationKey(place), "story"));
1532
- if (place !== void 0 && text !== "") lines.push(`${place.name} (${locationKey(place)}): ${text}`);
1533
- for (const entry of session.items.contents({
1534
- kind: "location",
1535
- id: here
1536
- })) {
1537
- const text = describeShown(shownVariables(session, "item", entry.item.id, itemKey(entry.item), "story"));
1538
- if (text !== "") lines.push(`${entry.item.name} (${itemKey(entry.item)}): ${text}`);
1539
- }
1540
- }
1541
- for (const character of [...session.characters.list()].sort((a, b) => near(a.id) - near(b.id))) {
1542
- const text = describeShown(shownVariables(session, "character", character.id, keyOfCharacter(character), "story"));
1543
- if (text !== "") lines.push(`${character.name} (${keyOfCharacter(character)}): ${text}`);
1544
- }
1545
- return lines.slice(0, MAX_TRACKED_LINES);
1546
- }
1547
- function checkMove(session, characterKey, request) {
1548
- const character = session.characters.list().find((candidate) => keyOfCharacter(candidate) === characterKey);
1549
- if (character === void 0) return {
1550
- ok: false,
1551
- problems: [`there is no character "${characterKey}"`]
1552
- };
1553
- const to = session.locations.list().find((candidate) => locationKey(candidate) === request.location);
1554
- if (to === void 0) return {
1555
- ok: false,
1556
- problems: [`there is no place "${request.location}" (list_locations shows the keys)`]
1557
- };
1558
- const move = {
1559
- to: to.id,
1560
- ...request.position === void 0 ? {} : { position: request.position },
1561
- ...request.feature === void 0 ? {} : { featureKey: request.feature },
1562
- ...request.ignoreExits === true ? { ignoreExits: true } : {}
1563
- };
1564
- const planned = session.planKnownMove(character.id, move);
1565
- return planned.ok ? {
1566
- ok: true,
1567
- move,
1568
- plan: planned.plan,
1569
- to: {
1570
- key: locationKey(to),
1571
- name: to.name
1572
- },
1573
- ...request.position === void 0 ? {} : { position: request.position }
1574
- } : {
1575
- ok: false,
1576
- problems: planned.problems
1577
- };
1578
- }
1579
- function storeOf(session, folder, problem, queryVector, wall, prompt) {
1580
- const settings = () => liveSettings(folder, problem);
1581
- return {
1582
- story: session,
1583
- cast: () => castOf(session),
1584
- checkMove: (character, request) => checkMove(session, character, request),
1585
- place: (locationId) => placeViewOf(session, locationId),
1586
- settings,
1587
- text: (id, variables) => prompt(settings().prompts.language, id, variables),
1588
- rules: () => rulesOf(worldRules(session), settings().rules.own),
1589
- time: (turn) => readTime(session, settings().clock, turn, wall()),
1590
- beginTurn: (turn) => {
1591
- observeAsPlayer(session, turn);
1592
- return startTurn(session, settings().clock, turn, wall());
1593
- },
1594
- endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum),
1595
- skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request),
1596
- checkVariableChanges: (changes) => changes.flatMap((spec) => {
1597
- const planned = planVariableChange(session, spec);
1598
- return planned.ok ? [] : planned.problems;
1599
- }),
1600
- changeVariables: (turn, changes) => session.transaction(() => changes.map((spec) => changeVariable(session, spec, turn))),
1601
- trackedFor: (characterId, presentIds) => trackedFor(session, characterId, presentIds),
1602
- tracked: () => trackedLines(session),
1603
- dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now, languageOf(settings().prompts.language)),
1604
- markHandled: (keys) => {
1605
- markHandled(session, keys);
1606
- },
1607
- runTriggers: (turn, round) => {
1608
- const settings = liveSettings(folder, problem);
1609
- const { now, zone } = readTime(session, settings.clock, turn, wall());
1610
- return fireTriggers(session, {
1611
- settings,
1612
- turn,
1613
- round,
1614
- now,
1615
- zone,
1616
- problem
1617
- });
1618
- },
1619
- ...noteStore(session, () => liveSettings(folder, problem), (turn) => {
1620
- const { now, zone } = readTime(session, liveSettings(folder, problem).clock, turn, wall());
1621
- return {
1622
- now,
1623
- zone
1624
- };
1625
- }),
1626
- putNote: (note) => {
1627
- putNote(session, note);
1628
- },
1629
- addNote: (kind, turn, lines) => {
1630
- addToNote(session, kind, turn, lines);
1631
- },
1632
- recordActivity: (entry, detail) => {
1633
- if (detail !== void 0 && entry.run !== void 0) keepRunDetail(folder, entry.run, detail);
1634
- forgetRunDetails(folder, recordActivity(session, entry));
1635
- },
1636
- notes: () => readNotes(session),
1637
- clearNotes: () => {
1638
- clearNotes(session);
1639
- },
1640
- agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId),
1641
- commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items }) => {
1642
- session.characterStates.update(character, patch);
1643
- const effects = (items ?? []).map((spec) => changeItem(session, character, spec));
1644
- if (move !== void 0) session.move(character, move);
1645
- return effects;
1646
- })),
1647
- checkItemChanges: (entries) => dryRunItems(session, entries),
1648
- carried: (characterId) => carriedBy(session, characterId),
1649
- knowledge: (characterId, turn, visibleCharacters) => knowledgeOf(session, characterId, turn, visibleCharacters),
1650
- affiliations: (characterId) => affiliationsOf(session, characterId),
1651
- itemsAt: (locationId, withHidden = false) => itemsIn(session, locationId, withHidden),
1652
- completeTurn: () => {
1653
- session.metadata.recordTurn();
1654
- },
1655
- queueCommit: (record) => {
1656
- session.pendingCommits.enqueue(record.turn, record.round, JSON.parse(JSON.stringify(record)));
1657
- },
1658
- pendingCommits: () => session.pendingCommits.list().map((entry) => entry.payload),
1659
- completeCommits: (rounds) => {
1660
- session.transaction(() => {
1661
- session.events.seal();
1662
- session.pendingCommits.complete(rounds);
1663
- });
1664
- },
1665
- queryVector
1666
- };
1667
- }
1668
- /** Opens the store of the roleplay session behind a chat; a chat that is not one gets none. */
1669
- function storesOf(state, sessionsDir, problem = () => void 0, queryVector = () => Promise.resolve(void 0), wall = Date.now, prompt = (language, id, variables) => shippedText(id, language, variables)) {
1670
- return (chat) => {
1671
- const id = roleplaySessionOf(chat);
1672
- if (id === void 0) return void 0;
1673
- try {
1674
- return storeOf(state.openSession(sessionsDir(), id), sessionFolder(sessionsDir(), id), problem, (text, signal) => queryVector(chat, text, signal), wall, (language, name, variables) => prompt(language, name, variables, id));
1675
- } catch {
1676
- return;
1677
- }
1678
- };
1679
- }
1680
- //#endregion
1681
- //#region src/shared/ooc.ts
1682
- /** 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. */
1683
- const OOC_COMMAND = /^\s*\/(ooc|ask)(?=\s|$)\s*([\s\S]*)$/i;
1684
- /** The command or question in a player's message, or nothing when the message is an ordinary action. The request may be empty. */
1685
- function parseOoc(text) {
1686
- const match = OOC_COMMAND.exec(text);
1687
- return match === null ? void 0 : {
1688
- request: (match[2] ?? "").trim(),
1689
- question: match[1].toLowerCase() === "ask"
1690
- };
1691
- }
1692
- /** The longest answer to an out-of-character question. */
1693
- const MAX_OOC_ANSWER = 1200;
1694
- //#endregion
1695
- //#region src/host/orchestration/hooks.ts
1696
- const notice = (text) => createUserMessage({
1697
- content: [{
1698
- type: "text",
1699
- text
1700
- }],
1701
- source: { kind: "roleplay" }
1702
- });
1703
- /** The turn of the game master of a roleplay chat; characters and other chats have none. */
1704
- function ownerOf(agent, turn) {
1705
- if (agent.session.header.origin === "subagent") return void 0;
1706
- return roleplaySessionOf(agent.session.id) === void 0 ? void 0 : {
1707
- chat: agent.session.id,
1708
- turn
1709
- };
1710
- }
1711
- /** 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. */
1712
- const PREVIEW_SHOWN = Symbol.for("dsh-agentic-roleplay.preview-tool");
1713
- /** Registers the preview tool on the agent of a chat that shows one, once, and withdraws it when the setting is turned off. */
1714
- function previewToggle(tool) {
1715
- return (agent, enabled) => {
1716
- const holder = agent;
1717
- const withdraw = holder[PREVIEW_SHOWN];
1718
- if (enabled && withdraw === void 0) try {
1719
- holder[PREVIEW_SHOWN] = agent.ctx.tools.register(tool);
1720
- } catch (error) {
1721
- if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
1722
- holder[PREVIEW_SHOWN] = () => void 0;
1723
- }
1724
- else if (!enabled && withdraw !== void 0) {
1725
- delete holder[PREVIEW_SHOWN];
1726
- withdraw();
1727
- }
1728
- };
1729
- }
1730
- /**
1731
- * The listeners of a roleplay preset. Preset listeners are shared by every chat
1732
- * that uses the preset and also hear the agents that chat spawns, so each one
1733
- * first checks that it is looking at the game master of a roleplay chat.
1734
- */
1735
- function installHooks(ctx, deps) {
1736
- const { engine, boundaries, stores, timelines, previewTool } = deps;
1737
- const showPreviewTool = previewToggle(previewTool);
1738
- ctx.on("session/event", (session, event) => {
1739
- if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
1740
- timelines.ended(session.id, session, event.seq);
1741
- });
1742
- ctx.on("agent/created", async ({ agent }) => {
1743
- const { header } = agent.session;
1744
- if (header.origin === "subagent" || !header.isSeeded || header.parentSession === void 0) return;
1745
- if (roleplaySessionOf(agent.session.id) === void 0 || roleplaySessionOf(header.parentSession) === void 0) return;
1746
- await timelines.adopt(agent.session.id, header.parentSession, agent.session.inheritedEventCount - 1, agent);
1747
- });
1748
- ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
1749
- const owner = ownerOf(agent, turn);
1750
- if (owner === void 0) return;
1751
- const missing = engine.missing(owner);
1752
- if (missing === void 0) return;
1753
- if (!engine.object(owner)) {
1754
- ctx.logger.warn(`roleplay: ${owner.chat} ended turn ${turn} without finishing it (${missing})`);
1755
- return;
1756
- }
1757
- agent.steer(notice(`You may not end the turn yet: ${missing}.`));
1758
- });
1759
- ctx.on("agent/pre-step", async (payload, next) => {
1760
- const decision = await next();
1761
- const owner = ownerOf(payload.agent, payload.turn);
1762
- const store = owner === void 0 ? void 0 : stores(owner.chat);
1763
- if (owner !== void 0 && store !== void 0) showPreviewTool(payload.agent, store.settings().preview.enabled);
1764
- if (decision.kind !== "enter" || payload.step !== 1) return decision;
1765
- if (owner === void 0 || store === void 0) return decision;
1766
- const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
1767
- await timelines.begin(owner.chat, payload.turn, text);
1768
- const cast = store.cast();
1769
- const ooc = parseOoc(text);
1770
- const verdict = ooc === void 0 ? boundaries().inputValidator.validate({
1771
- text,
1772
- turn: payload.turn,
1773
- cast
1774
- }) : { ok: true };
1775
- if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
1776
- else if (ooc === void 0) engine.expectJudgement(owner);
1777
- const queryVector = await store.queryVector(ooc?.request ?? text);
1778
- store.clearNotes();
1779
- store.lapseNotes(payload.turn);
1780
- const { time, away, agenda } = store.beginTurn(payload.turn);
1781
- const tr = translator(languageOf(store.settings().prompts.language));
1782
- if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => tr("{name} went to {place}.", {
1783
- name: move.name,
1784
- place: move.to
1785
- })));
1786
- const world = {
1787
- happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
1788
- names: cue.names.join(tr(" and ")),
1789
- text: cue.text
1790
- }))]),
1791
- beats: store.pendingBeats(),
1792
- upcoming: store.upcoming(payload.turn)
1793
- };
1794
- const tracked = store.tracked();
1795
- const lines = [boundaries().sceneContext.scene({
1796
- ...tracked.length === 0 ? {} : { tracked },
1797
- time: {
1798
- now: time,
1799
- agenda,
1800
- ...away === void 0 ? {} : { away }
1801
- },
1802
- ...world.happened.length === 0 && world.beats.length === 0 && world.upcoming.length === 0 ? {} : { world },
1803
- cast,
1804
- turn: payload.turn,
1805
- input: text,
1806
- story: store.story,
1807
- items: {
1808
- at: (locationId) => store.itemsAt(locationId, true),
1809
- carried: (characterId) => store.carried(characterId)
1810
- },
1811
- language: store.settings().prompts.language,
1812
- ...queryVector === void 0 ? {} : { queryVector }
1813
- })];
1814
- const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
1815
- if (pacing !== void 0) lines.push(describePacingAdvice(pacing));
1816
- else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
1817
- const rules = store.rules();
1818
- if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
1819
- if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
1820
- if (ooc !== void 0 && ooc.request === "") {
1821
- engine.skip(owner);
1822
- lines.push(store.text("roleplay/ooc-empty", { command: ooc.question ? "/ask" : "/ooc" }));
1823
- }
1824
- if (!verdict.ok) {
1825
- engine.skip(owner);
1826
- lines.push(store.text("roleplay/input-refused", { reason: verdict.reason }));
1827
- }
1828
- return {
1829
- ...decision,
1830
- messages: [...decision.messages, notice(lines.join("\n\n"))]
1831
- };
1832
- });
1833
- }
1834
- //#endregion
1835
935
  //#region src/host/orchestration/prompt.ts
1836
936
  const PROTOCOL_SECTION = "roleplay:protocol";
1837
937
  const PERSONA_SECTION = "roleplay:persona";
1838
938
  //#endregion
939
+ //#region src/host/dice/describe.ts
940
+ /** The checks of a story as the game master is told of them: when each is used, what it rolls and what it needs. The result's bands are told by the roll itself. */
941
+ function describeChecks(checks, tr) {
942
+ if (checks.length === 0) return tr("No checks are defined: use roll_dice only.");
943
+ const lines = checks.map((check) => {
944
+ const needs = [
945
+ tr("Rolls {dice}.", { dice: check.dice }),
946
+ ...check.reading === "successes" ? [tr("Counts the dice that show {hit} or more.", { hit: check.hit ?? 0 })] : [],
947
+ ...check.compare === "over" ? [tr("Give a target: the difficulty, the number to meet or beat; set it by how hard the attempt is.")] : check.compare === "under" ? [tr("Give a target: the number to stay under; set it by how hard the attempt is.")] : [],
948
+ ...check.modifier === void 0 ? [] : [tr("It adds the character's {variable}.", { variable: check.modifier })]
949
+ ];
950
+ return `${tr("- {key} ({name}): {use}", {
951
+ key: check.key,
952
+ name: check.name,
953
+ use: check.use.replace(/[.\s]+$/, "")
954
+ })}. ${needs.join(" ")}`;
955
+ });
956
+ return [tr("The checks of this story:"), ...lines].join("\n");
957
+ }
958
+ //#endregion
1839
959
  //#region src/host/orchestration/current-turn.ts
1840
960
  /** The last turn the session started. */
1841
961
  function currentTurn(agent) {
@@ -1847,1040 +967,26 @@ function currentTurn(agent) {
1847
967
  return 0;
1848
968
  }
1849
969
  //#endregion
1850
- //#region src/host/orchestration/character-runner.ts
970
+ //#region src/host/memory/embedding-index.ts
971
+ const BATCH = 32;
1851
972
  /**
1852
- * Runs each character as a one-shot child of the game master. It is the character and nothing
1853
- * else: it knows what its brief gives it, and its only tool (when the chat allows it) reaches
1854
- * the memory of that character alone, so characters acting at the same time cannot see each
1855
- * other's memories.
973
+ * Keeps the vectors of a chat's texts: embeds what has none yet, and gives the vector of a moment to
974
+ * search with. The story knows which texts wait and keeps the vectors; this is the only part that
975
+ * talks to an embedding service. Everything degrades to searching by words: without a service, a
976
+ * provider that fails, or vectors made by another model than the one now selected, the search
977
+ * simply has no vector to use.
1856
978
  */
1857
- function characterRunner(deps) {
1858
- return async (request, signal) => {
1859
- const brief = deps.boundaries().characterContext.brief(request);
1860
- const tools = request.lookup ? createCharacterTools(() => ({
1861
- session: deps.store.story,
1862
- turn: request.turn,
1863
- policy: deps.store.settings().memory,
1864
- queryVector: deps.store.queryVector
1865
- }), request.member.character.id) : [];
1866
- const settings = deps.store.settings();
1867
- const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
1868
- const result = await runChild({
1869
- parent: deps.parent,
1870
- signal,
1871
- sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
1872
- ...childModel(settings, "characters", named),
1873
- trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named),
1874
- reasoningEffort: deps.store.settings().reasoning.children,
1875
- persona: brief.persona,
1876
- prompt: brief.prompt,
1877
- tools,
1878
- maxCalls: deps.store.settings().memory.lookupCalls,
1879
- result: request.away === true ? AWAY_ACTION_SCHEMA : CHARACTER_ACTION_SCHEMA,
1880
- unenforced: ["thought"],
1881
- beforeSubmit: (value) => spokenIn(settings.prompts.language, value)
1882
- });
1883
- return parseCharacterAction(result);
1884
- };
1885
- }
1886
- /** A character whose sheet is in another language than the chat's writes in the sheet's: the answer is refused until it is in the chat's. */
1887
- function spokenIn(language, value) {
1888
- const given = value;
1889
- return wrongLanguage(language, {
1890
- thought: given.thought,
1891
- intent: given.intent,
1892
- utterance: given.utterance,
1893
- account: given.account
1894
- });
1895
- }
1896
- /** What the character was reminded of and why, for the run's record, when the recall said why. */
1897
- function recalledOf(request) {
1898
- const explained = (request.memories ?? []).filter((memory) => memory.why !== void 0);
1899
- return explained.length === 0 ? {} : { recalled: explained.slice(0, 30).map(({ clarity, turn, text, why }) => ({
1900
- clarity,
1901
- turn,
1902
- text,
1903
- why
1904
- })) };
1905
- }
1906
- const ANSWER_SCHEMA = {
1907
- type: "object",
1908
- properties: { answer: {
1909
- type: "string",
1910
- description: "The answer to the player, in plain words, in a few sentences."
1911
- } },
1912
- required: ["answer"],
1913
- additionalProperties: false
1914
- };
1915
- /**
1916
- * 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
1917
- * game master alone knows is in the prompt, so the answer cannot give away what the character could not know.
1918
- */
1919
- function answerRunner(deps) {
1920
- return async (request, signal) => {
1921
- const brief = deps.boundaries().characterContext.brief(request);
1922
- return (await runChild({
1923
- parent: deps.parent,
1924
- signal,
1925
- sampling: childSampling(deps.store.settings(), "records", estimateAnswer([MAX_OOC_ANSWER], deps.store.settings().prompts.language)),
1926
- ...childModel(deps.store.settings(), "records"),
1927
- trace: childTrace(deps.store, "records", "answer to the player"),
1928
- reasoningEffort: deps.store.settings().reasoning.children,
1929
- persona: request.text("roleplay/ask-answerer", { name: request.member.character.name }),
1930
- prompt: brief.prompt,
1931
- tools: [],
1932
- maxCalls: 3,
1933
- result: ANSWER_SCHEMA
1934
- })).answer;
1935
- };
1936
- }
1937
- //#endregion
1938
- //#region src/host/orchestration/boundaries.ts
1939
- /** Why the game master may ask for something to be made up: the story genuinely needs it. */
1940
- const AUTHORING_NEEDS = [
1941
- "scene_change",
1942
- "arrival",
1943
- "introduction",
1944
- "object",
1945
- "variable",
1946
- "trigger"
1947
- ];
1948
- //#endregion
1949
- //#region src/host/pacing/author.ts
1950
- const RESULT = {
1951
- type: "object",
1952
- required: [
1953
- "id",
1954
- "name",
1955
- "premise",
1956
- "themes",
1957
- "hook",
1958
- "developments",
1959
- "stakes",
1960
- "resolutions",
1961
- "participants"
1962
- ],
1963
- additionalProperties: false,
1964
- properties: {
1965
- id: { type: "string" },
1966
- name: { type: "string" },
1967
- premise: { type: "string" },
1968
- themes: {
1969
- type: "array",
1970
- items: { type: "string" }
1971
- },
1972
- hook: {
1973
- type: "object",
1974
- required: [
1975
- "id",
1976
- "text",
1977
- "guidance",
1978
- "avoid"
1979
- ],
1980
- additionalProperties: false,
1981
- properties: {
1982
- id: { type: "string" },
1983
- text: { type: "string" },
1984
- guidance: { type: "string" },
1985
- avoid: {
1986
- type: "array",
1987
- items: { type: "string" }
1988
- }
1989
- }
1990
- },
1991
- developments: {
1992
- type: "array",
1993
- items: {
1994
- type: "object",
1995
- required: [
1996
- "id",
1997
- "text",
1998
- "mode",
1999
- "prerequisites",
2000
- "guidance",
2001
- "avoid"
2002
- ],
2003
- additionalProperties: false,
2004
- properties: {
2005
- id: { type: "string" },
2006
- text: { type: "string" },
2007
- mode: {
2008
- type: "string",
2009
- enum: [
2010
- "opportunity",
2011
- "reminder",
2012
- "character",
2013
- "consequence",
2014
- "escalation",
2015
- "breathing_room"
2016
- ]
2017
- },
2018
- prerequisites: {
2019
- type: "array",
2020
- items: { type: "string" }
2021
- },
2022
- guidance: { type: "string" },
2023
- avoid: {
2024
- type: "array",
2025
- items: { type: "string" }
2026
- }
2027
- }
2028
- }
2029
- },
2030
- stakes: {
2031
- type: "array",
2032
- items: { type: "string" }
2033
- },
2034
- resolutions: {
2035
- type: "array",
2036
- items: { type: "string" }
2037
- },
2038
- participants: {
2039
- type: "array",
2040
- items: { type: "string" }
2041
- }
2042
- }
2043
- };
2044
- /** A scaffold is about two dozen short texts: premise, hook, developments with their guidance, stakes and resolutions. */
2045
- const PLOT_TEXTS = 24;
2046
- const PLOT_TEXT_CHARS = 300;
2047
- async function authorPlot(parent, store, turn, signal) {
2048
- const cast = store.cast().map((member) => `${member.character.name} (${member.key}): ${member.character.summary}`).join("\n");
2049
- const factions = store.story.factions.list().map((faction) => `${faction.name} (${faction.sourceId ?? faction.id}): ${faction.summary}`).join("\n");
2050
- const places = store.story.locations.list().map((place) => `${place.name} (${place.sourceId ?? place.id})`).join(", ");
2051
- const events = store.story.events.list().slice(-12).map((event) => `- ${event.text}`).join("\n");
2052
- let checked;
2053
- const result = await runChild({
2054
- parent,
2055
- signal,
2056
- sampling: childSampling(store.settings(), "authoring", estimateAnswer(Array.from({ length: PLOT_TEXTS }, () => PLOT_TEXT_CHARS), store.settings().prompts.language)),
2057
- ...childModel(store.settings(), "authoring"),
2058
- trace: childTrace(store, "authoring", "plot author"),
2059
- persona: promptFor(parent, "roleplay/plot-author", store.settings().prompts.language),
2060
- reasoningEffort: store.settings().reasoning.children,
2061
- result: RESULT,
2062
- maxCalls: 3,
2063
- prompt: `The story has gone quiet by turn ${turn}. Propose one optional plot scaffold that grows from this state.\n\nCharacters:\n${cast || "- none"}\n\nFactions:\n${factions || "- none"}\n\nPlaces: ${places || "none"}\n\nRecent recorded events:\n${events || "- none"}`,
2064
- beforeSubmit(value) {
2065
- const authored = value;
2066
- const candidate = {
2067
- ...authored,
2068
- hooks: [{
2069
- ...authored.hook,
2070
- mode: "opportunity",
2071
- prerequisites: []
2072
- }],
2073
- start: "available",
2074
- pacing: {
2075
- quietTurns: 3,
2076
- cooldownTurns: 4,
2077
- cooldownDays: 1
2078
- }
2079
- };
2080
- const parsed = parsePlotsFile(JSON.stringify([candidate]));
2081
- if (!parsed.ok) return parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n");
2082
- checked = parsed.value[0];
2083
- }
2084
- });
2085
- if (checked === void 0) throw new Error(`the plot author returned an invalid plot: ${result.name}`);
2086
- addSessionPlot(store, checked);
2087
- return checked;
2088
- }
2089
- //#endregion
2090
- //#region src/host/orchestration/tools.ts
2091
- const ACTIVATE_TOOL = "activate_characters";
2092
- const RESOLVE_TOOL = "resolve_round";
2093
- const NARRATE_TOOL = "narrate";
2094
- const RECORD_TOOL = "record_memory";
2095
- const EXPAND_TOOL = "expand_world";
2096
- const INTRODUCE_TOOL = "introduce_thing";
2097
- const TIME_TOOL = "advance_time";
2098
- const PREVIEW_TOOL = "preview_scene";
2099
- const RULING_TOOL = "ooc_ruling";
2100
- const ANSWER_TOOL = "ooc_answer";
2101
- const JUDGE_TOOL = "judge_action";
2102
- const PLOT_TOOL = "record_plot_progress";
2103
- const AUTHOR_PLOT_TOOL = "author_plot";
2104
- /** The JSON value the tool records; the model reads the rendered text. */
2105
- function record(value) {
2106
- return JSON.parse(JSON.stringify(value));
2107
- }
2108
- function failures(list) {
2109
- return list.length === 0 ? [] : [
2110
- "",
2111
- "Could not act:",
2112
- ...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}`)
2113
- ];
2114
- }
2115
- function renderAttempt(attempt) {
2116
- const heading = attempt.attempt === 1 ? "The characters acted. Their intents may conflict with each other; you decide what actually happens." : "These characters failed but were highly committed, so each tried once more, knowing what just happened.";
2117
- const lines = attempt.reports.map((report) => `- ${report.character} (${report.name}): ${report.utterance === void 0 ? "says nothing" : `says "${report.utterance}"`}; does: ${report.intent} [commitment: ${report.commitment}]`);
2118
- const next = attempt.reports.length === 0 ? ["", "Nobody could act. Fix the problem or call activate_characters again with a different set."] : attempt.attempt === 1 ? ["", `Now call ${RESOLVE_TOOL} with one outcome for each of: ${attempt.reports.map((report) => report.character).join(", ")}.`] : ["", `Call ${RESOLVE_TOOL} once more with one outcome for each of: ${attempt.reports.map((report) => report.character).join(", ")}. There are no further retries: what you decide now is final.`];
2119
- return [
2120
- heading,
2121
- ...lines,
2122
- ...failures(attempt.failures),
2123
- ...next
2124
- ].join("\n");
2125
- }
2126
- /** Who went where because their day says so. */
2127
- const routineLine = (move) => `By their routine, ${move.name} is now at ${move.to} (${move.activity}).`;
2128
- const OUTPUT_RULES = "Deliver the output with the narrate tool as ordered segments: utterances and narration. Narration may come before, between and after utterances and is yours to write. Utterances are the characters' words: include every one exactly as given, once, in the order they were spoken, and never change, add or remove one.";
2129
- const listed = (utterances) => utterances.map((utterance) => `- ${utterance.character} (${utterance.name}), round ${utterance.round}: "${utterance.text}"`).join("\n");
2130
- /** What the world did by itself, as the game master is told: what happened, what characters notice, and what it is to weave in. */
2131
- function renderWorld(world) {
2132
- return world.flatMap((entry) => [
2133
- ...entry.events.map((text) => `The world acted (${entry.name}): ${text}`),
2134
- ...entry.cues.map((cue) => `${cue.names.join(" and ")} will notice: ${cue.text}`),
2135
- ...entry.beats.map((beat) => `Weave this into the story, then say you did with addressed: [${beat.id}] in narrate (${beat.text})`)
2136
- ]);
2137
- }
2138
- function renderResolution(report) {
2139
- if (report.next !== void 0) return renderAttempt(report.next);
2140
- const done = report.done;
2141
- if (done === void 0) return "";
2142
- const left = done.limit - done.round;
2143
- const passed = done.time.to - done.time.from;
2144
- const lines = [
2145
- `Round ${done.round} is recorded (${done.updated.join(", ")}).`,
2146
- `It is now ${describeTime({
2147
- now: done.time.to,
2148
- zone: done.time.zone
2149
- })}${passed > 0 ? `; ${describeDuration(passed)} passed` : ""}.`,
2150
- ...done.moved.map(routineLine),
2151
- ...done.moves.map((move) => `${move.name} is now at ${move.to}${move.via > 0 ? ` (by way of ${move.via} other place${move.via === 1 ? "" : "s"})` : ""}.`),
2152
- ...done.things.map((thing) => `${thing.name}: ${thing.summary}.`),
2153
- ...done.variables.map((line) => `${line}.`),
2154
- ...renderWorld(done.world),
2155
- ...failures(done.retryFailures)
2156
- ];
2157
- lines.push(done.spoken.length === 0 ? "Nobody has said anything yet this turn." : `Everything said so far this turn, in order; the output must carry all of it exactly:\n${listed(done.spoken)}`);
2158
- lines.push(left > 0 ? `Now decide. If the story genuinely flows from what just happened (someone is directly answered, a reaction is natural, something is left unresolved that the characters would act on), call activate_characters for the next round: ${left} round(s) are left for this message. Otherwise give control back to the player now.` : "That was the last round allowed for this message: give control back to the player now.");
2159
- lines.push(done.waiting === 0 ? "Nothing is waiting to be recorded." : `${done.waiting} round${done.waiting === 1 ? " is" : "s are"} waiting to be recorded in the story's memory. Memory is not written after every round: call ${RECORD_TOOL} when the story just moved on (a decision made, a secret or fact revealed, a promise, an injury, a relationship changed, the scene or time moved); skip it for small talk and routine movement, which are kept and recorded together with the next thing that matters.`);
2160
- lines.push(OUTPUT_RULES);
2161
- lines.push("Narrate only what the player's character can perceive.");
2162
- return lines.join("\n");
2163
- }
2164
- function renderExpansion(report) {
2165
- if (report.created.length === 0) return `Nothing was made up: ${(report.declined ?? "the world author found nothing the story needs").replace(/[.\s]+$/, "")}. Work with what exists.`;
2166
- const lines = report.created.map((entry) => `- ${entry.kind} ${entry.key} (${entry.name})`);
2167
- const characters = report.created.filter((entry) => entry.kind === "character");
2168
- return [
2169
- "Made up and fitted into the world:",
2170
- ...lines,
2171
- ...characters.length === 0 ? [] : [`${characters.length === 1 ? "They are" : "They are all"} now in the cast: ask them to act with ${ACTIVATE_TOOL}, by their keys, like anyone else.`],
2172
- ...report.declined === void 0 ? [] : [`Not made: ${report.declined}`]
2173
- ].join("\n");
2174
- }
2175
- /** The tools the game master plays a turn with. */
2176
- function createTools$1(deps) {
2177
- const ownerOf = (agent) => {
2178
- if (agent === void 0) throw new Error("the roleplay tools can only be called by an agent");
2179
- return {
2180
- agent,
2181
- owner: {
2182
- chat: agent.session.id,
2183
- turn: deps.turnOf(agent)
2184
- }
2185
- };
2186
- };
2187
- const storeOf = (chat) => {
2188
- const store = deps.stores(chat);
2189
- if (store === void 0) throw new Error("this chat is not a roleplay session");
2190
- return store;
2191
- };
2192
- const activate = defineTool({
2193
- name: ACTIVATE_TOOL,
2194
- 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.",
2195
- parameters: {
2196
- characters: {
2197
- type: "array",
2198
- required: true,
2199
- items: { type: "string" },
2200
- 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."
2201
- },
2202
- situation: {
2203
- type: "string",
2204
- required: true,
2205
- 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."
2206
- }
2207
- },
2208
- output: {
2209
- schema: { type: "json" },
2210
- render: (_args, value) => [{
2211
- type: "text",
2212
- text: renderAttempt(value)
2213
- }]
2214
- },
2215
- isConcurrencySafe: () => false,
2216
- async execute(args, exec) {
2217
- const { agent, owner } = ownerOf(exec.agent);
2218
- await deps.engine.settle(owner.chat, owner.turn);
2219
- const run = characterRunner({
2220
- parent: agent,
2221
- boundaries: deps.boundaries,
2222
- store: storeOf(owner.chat)
2223
- });
2224
- return record(await deps.engine.activate(owner, {
2225
- situation: args.situation,
2226
- characters: args.characters
2227
- }, run, exec.signal));
2228
- }
2229
- });
2230
- const resolve = defineTool({
2231
- name: RESOLVE_TOOL,
2232
- 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.",
2233
- parameters: {
2234
- outcomes: {
2235
- type: "array",
2236
- required: true,
2237
- items: {
2238
- type: "object",
2239
- additionalProperties: false,
2240
- properties: {
2241
- character: {
2242
- type: "string",
2243
- required: true,
2244
- description: "The character's key; for the player's character, only when it moves or handles things; in an out-of-character command, any character of the story."
2245
- },
2246
- result: {
2247
- type: "string",
2248
- required: true,
2249
- enum: RESULTS,
2250
- description: "Whether the character's intent went through."
2251
- },
2252
- summary: {
2253
- type: "string",
2254
- required: true,
2255
- description: "What concretely happens to the character, in a sentence. It becomes what the character is doing."
2256
- },
2257
- spoken: {
2258
- type: "boolean",
2259
- description: "Whether the character gets to say its utterance. It does unless something prevents it, such as being silenced or knocked out first."
2260
- },
2261
- public_state: {
2262
- type: "string",
2263
- description: "What anyone present can now see or infer about the character, when that changed."
2264
- },
2265
- item_changes: {
2266
- type: "array",
2267
- description: "What the character does with things as a result, in order, when it does: leave out when it handles nothing. Each is checked, and you are told why when it cannot be done. Not for a character whose intent failed.",
2268
- items: {
2269
- type: "object",
2270
- additionalProperties: false,
2271
- properties: {
2272
- item: {
2273
- type: "string",
2274
- required: true,
2275
- description: "The key of the item, as the scene lists it. Leave a way's lock to exit."
2276
- },
2277
- action: {
2278
- type: "string",
2279
- required: true,
2280
- enum: ITEM_ACTIONS,
2281
- description: "take (pick up what is here or take it out of a container it carries), drop (leave it here), give (to someone present), put (into an open container), wear, remove (what is worn), open, close, lock, unlock, reveal (find what was hidden)."
2282
- },
2283
- to: {
2284
- type: "string",
2285
- description: "For give: who gets it. For put: the container."
2286
- },
2287
- quantity: {
2288
- type: "integer",
2289
- description: "How many, of a pile; all when left out."
2290
- },
2291
- position: {
2292
- type: "string",
2293
- description: "Where, in words, for drop and put."
2294
- },
2295
- feature: {
2296
- type: "string",
2297
- description: "For drop: the feature of the place it is left at."
2298
- },
2299
- with: {
2300
- type: "string",
2301
- description: "For lock and unlock: the key item used. It has to be in hand and fit the lock."
2302
- },
2303
- exit: {
2304
- type: "string",
2305
- description: "For lock and unlock of a way instead of an item: the key of the place it leads to."
2306
- },
2307
- forced: {
2308
- type: "boolean",
2309
- description: "Only when the story breaks the lock (picked, smashed): no key is needed."
2310
- }
2311
- }
2312
- }
2313
- },
2314
- variable_changes: {
2315
- type: "array",
2316
- description: "What this changes of what the story keeps track of (the scene lists it; list_variables shows what exists): a feeling, an injury, a flag, a debt. Only what the outcome establishes; to is the new value (a number, true or false, or one of the words of a choice), by is an amount a number goes up or down (it stops at its bounds).",
2317
- items: {
2318
- type: "object",
2319
- additionalProperties: false,
2320
- properties: {
2321
- variable: {
2322
- type: "string",
2323
- required: true,
2324
- description: "The key of the variable."
2325
- },
2326
- subject: {
2327
- type: "string",
2328
- required: true,
2329
- description: "The key of the character, item or place it is about; world for the whole story."
2330
- },
2331
- to: {
2332
- oneOf: [
2333
- { type: "number" },
2334
- { type: "boolean" },
2335
- { type: "string" }
2336
- ],
2337
- description: "The new value."
2338
- },
2339
- by: {
2340
- type: "number",
2341
- description: "How much a number goes up (positive) or down (negative)."
2342
- },
2343
- baseline: {
2344
- oneOf: [
2345
- { type: "number" },
2346
- { type: "boolean" },
2347
- { type: "string" }
2348
- ],
2349
- description: "For a variable with a temperament (feelings): the new baseline, when what happened changes it lastingly."
2350
- }
2351
- }
2352
- }
2353
- },
2354
- moves_to: {
2355
- type: "object",
2356
- additionalProperties: false,
2357
- description: "Where the character ends up if it goes somewhere as a result: leave out when it stays. It must be possible (a way over open exits); you are told why if it is not. Not for a character whose intent failed. A journey takes at least as long as the ways on it say, whatever elapsed_seconds you give.",
2358
- properties: {
2359
- location: {
2360
- type: "string",
2361
- required: true,
2362
- description: "The key of the place, as the scene lists it."
2363
- },
2364
- position: {
2365
- type: "string",
2366
- description: "Where in the place, in words: \"by the window\"."
2367
- },
2368
- feature: {
2369
- type: "string",
2370
- description: "The key of a feature of that place it is at."
2371
- },
2372
- ignore_exits: {
2373
- type: "boolean",
2374
- description: "Only when the story itself carries it (carried off, teleported, falls): the exits do not matter."
2375
- }
2376
- }
2377
- }
2378
- }
2379
- }
2380
- },
2381
- elapsed_seconds: {
2382
- type: "integer",
2383
- 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."
2384
- }
2385
- },
2386
- output: {
2387
- schema: { type: "json" },
2388
- render: (_args, value) => [{
2389
- type: "text",
2390
- text: renderResolution(value)
2391
- }]
2392
- },
2393
- isConcurrencySafe: () => false,
2394
- async execute(args, exec) {
2395
- const { agent, owner } = ownerOf(exec.agent);
2396
- await deps.engine.settle(owner.chat, owner.turn);
2397
- const run = characterRunner({
2398
- parent: agent,
2399
- boundaries: deps.boundaries,
2400
- store: storeOf(owner.chat)
2401
- });
2402
- const outcomes = args.outcomes.map((outcome) => ({
2403
- character: outcome.character,
2404
- result: outcome.result,
2405
- summary: outcome.summary,
2406
- ...outcome.public_state === void 0 ? {} : { publicState: outcome.public_state },
2407
- ...outcome.spoken === void 0 ? {} : { spoken: outcome.spoken },
2408
- ...outcome.item_changes === void 0 || outcome.item_changes.length === 0 ? {} : { itemChanges: outcome.item_changes.map((change) => ({
2409
- item: change.item,
2410
- action: change.action,
2411
- ...change.to === void 0 ? {} : { to: change.to },
2412
- ...change.quantity === void 0 ? {} : { quantity: change.quantity },
2413
- ...change.position === void 0 ? {} : { position: change.position },
2414
- ...change.feature === void 0 ? {} : { feature: change.feature },
2415
- ...change.with === void 0 ? {} : { with: change.with },
2416
- ...change.exit === void 0 ? {} : { exit: change.exit },
2417
- ...change.forced === true ? { forced: true } : {}
2418
- })) },
2419
- ...outcome.variable_changes === void 0 || outcome.variable_changes.length === 0 ? {} : { variableChanges: outcome.variable_changes.map((change) => ({
2420
- variable: change.variable,
2421
- subject: change.subject,
2422
- ...change.to === void 0 ? {} : { to: change.to },
2423
- ...change.by === void 0 ? {} : { by: change.by },
2424
- ...change.baseline === void 0 ? {} : { baseline: change.baseline }
2425
- })) },
2426
- ...outcome.moves_to === void 0 ? {} : { moveTo: {
2427
- location: outcome.moves_to.location,
2428
- ...outcome.moves_to.position === void 0 ? {} : { position: outcome.moves_to.position },
2429
- ...outcome.moves_to.feature === void 0 ? {} : { feature: outcome.moves_to.feature },
2430
- ...outcome.moves_to.ignore_exits === true ? { ignoreExits: true } : {}
2431
- } }
2432
- }));
2433
- return record(await deps.engine.resolve(owner, outcomes, run, exec.signal, args.elapsed_seconds));
2434
- }
2435
- });
2436
- const narrate = defineTool({
2437
- name: NARRATE_TOOL,
2438
- description: "Deliver the output of the turn to the player and give control back to them, once at least one round is recorded: the characters' utterances from all the rounds and your narration, as ordered segments. Every utterance a character gave must appear exactly once, exactly as given and in the order spoken; narration is free. An output that changes, drops, invents or reorders an utterance is refused with what is wrong.",
2439
- parameters: {
2440
- segments: {
2441
- type: "array",
2442
- description: "The output in order. Leave out only when a narrator other than you writes the output.",
2443
- items: {
2444
- type: "object",
2445
- additionalProperties: false,
2446
- properties: {
2447
- type: {
2448
- type: "string",
2449
- required: true,
2450
- enum: ["utterance", "narration"]
2451
- },
2452
- character: {
2453
- type: "string",
2454
- description: "For an utterance: the key of the character who says it."
2455
- },
2456
- text: {
2457
- type: "string",
2458
- required: true,
2459
- description: "For an utterance: the words exactly as the character gave them, without quotation marks. For narration: what the player reads."
2460
- }
2461
- }
2462
- }
2463
- },
2464
- addressed: {
2465
- type: "array",
2466
- items: { type: "integer" },
2467
- description: "The ids of the beats you were told to weave in that this output does. Beats you do not address are told again, then let go."
2468
- }
2469
- },
2470
- output: {
2471
- schema: { type: "json" },
2472
- render: (_args, value) => {
2473
- const output = value;
2474
- return [{
2475
- type: "text",
2476
- text: `${output.repaired ? "The output was corrected so that every utterance appears exactly as the characters gave it, and has been delivered to the player. The turn ends here." : "The output has been delivered to the player. The turn ends here."}\n${encodeOutput(output)}`
2477
- }];
2478
- }
2479
- },
2480
- isConcurrencySafe: () => false,
2481
- async execute(args, exec) {
2482
- const { agent, owner } = ownerOf(exec.agent);
2483
- await deps.engine.settle(owner.chat, owner.turn);
2484
- const segments = (args.segments ?? []).map((segment) => ({
2485
- type: segment.type,
2486
- text: segment.text,
2487
- ...segment.character === void 0 ? {} : { character: segment.character }
2488
- }));
2489
- const output = await deps.engine.narrate(owner, segments, characterRunner({
2490
- parent: agent,
2491
- boundaries: deps.boundaries,
2492
- store: storeOf(owner.chat)
2493
- }), args.addressed ?? []);
2494
- const timelineNode = deps.delivered?.(owner.chat, output);
2495
- const delivered = timelineNode === void 0 ? output : {
2496
- ...output,
2497
- timelineNode
2498
- };
2499
- exec.concludeTurn();
2500
- return record(delivered);
2501
- }
2502
- });
2503
- const remember = defineTool({
2504
- name: RECORD_TOOL,
2505
- description: "Have the memory keeper write what happened since the last record into the story's lasting memory: the events, what each character took in of them, what they now believe, and the threads left open. It works in the background and covers every round still waiting, from this turn and earlier ones. Call it when the story changes phase, not after every round; rounds you do not record are kept and recorded together later.",
2506
- parameters: { focus: {
2507
- type: "string",
2508
- description: "What is worth keeping, in a sentence: the decision, revelation or change that matters. The keeper writes it first and may leave out incidental detail."
2509
- } },
2510
- output: {
2511
- schema: { type: "json" },
2512
- render: (_args, value) => [{
2513
- type: "text",
2514
- text: `The memory keeper is writing ${value.rounds} round${value.rounds === 1 ? "" : "s"} into the story's memory.`
2515
- }]
2516
- },
2517
- isConcurrencySafe: () => false,
2518
- execute(args, exec) {
2519
- const { owner } = ownerOf(exec.agent);
2520
- return Promise.resolve(record({ rounds: deps.engine.record(owner, args.focus) }));
2521
- }
2522
- });
2523
- const plot = defineTool({
2524
- name: PLOT_TOOL,
2525
- description: "Record only what play has already established about an optional plot. introduced means the named opportunity actually became perceptible in the resolved round, not merely that the pacing note suggested it. rejected means the player clearly declined that specific hook. resolved or abandoned applies to the plot as a whole. This records pacing state; it creates no event and makes nothing happen.",
2526
- parameters: {
2527
- plot: {
2528
- type: "string",
2529
- required: true,
2530
- description: "The plot id from the pacing opportunity."
2531
- },
2532
- development: {
2533
- type: "string",
2534
- description: "The development id; required for introduced or rejected."
2535
- },
2536
- action: {
2537
- type: "string",
2538
- required: true,
2539
- enum: [
2540
- "introduced",
2541
- "rejected",
2542
- "resolved",
2543
- "abandoned"
2544
- ]
2545
- }
2546
- },
2547
- output: {
2548
- schema: { type: "json" },
2549
- render: (_args, value) => [{
2550
- type: "text",
2551
- text: `Plot pacing recorded: ${value.plot.name} is ${value.status}.`
2552
- }]
2553
- },
2554
- isConcurrencySafe: () => false,
2555
- execute(args, exec) {
2556
- const { owner } = ownerOf(exec.agent);
2557
- return Promise.resolve(record(updatePlotProgress(storeOf(owner.chat), args.plot, args.development, args.action)));
2558
- }
2559
- });
2560
- const makePlot = defineTool({
2561
- name: AUTHOR_PLOT_TOOL,
2562
- description: "Ask a plot author for one optional, branching dramatic scaffold grounded in the current session. Use only when the scene explicitly says the quiet story has no plot scaffold and a reusable tension would help. It creates possibilities, not events, actions or obligations; do not introduce any part until a later pacing opportunity fits.",
2563
- parameters: {},
2564
- output: {
2565
- schema: { type: "json" },
2566
- render: (_args, value) => {
2567
- const made = value;
2568
- return [{
2569
- type: "text",
2570
- text: `Authored optional plot ${made.name} [${made.id}]: ${made.premise}. Nothing in it has happened. Continue this turn normally; a later pacing opportunity may offer a hook.`
2571
- }];
2572
- }
2573
- },
2574
- isConcurrencySafe: () => false,
2575
- async execute(_args, exec) {
2576
- const { agent, owner } = ownerOf(exec.agent);
2577
- const store = storeOf(owner.chat);
2578
- if (!plotAuthorNeeded(store, owner.turn)) throw new Error("the story does not currently need a plot author; continue with its existing plots, threads and character goals");
2579
- return record(await authorPlot(agent, store, owner.turn, exec.signal));
2580
- }
2581
- });
2582
- const expand = defineTool({
2583
- name: EXPAND_TOOL,
2584
- description: "Have a new character or place made up and fitted into the world, only when the story genuinely needs it. Valid reasons: scene_change (the story has actually gone somewhere that no known place covers, even as part of one), arrival (someone new has actually arrived or been brought into the scene), introduction (a specific person who has not appeared is needed by what is happening now and the story has established who they are), object (a thing so important or so complex that it needs inventing, such as an artifact with properties or a vehicle; or a place on the body that the world has no slot for; ordinary things the story uses are yours to bring in with introduce_thing), trigger (the story set up a moment that is bound to come, such as a deadline given, a promised arrival or a trap laid, that can be stated as a condition: a time, someone in a place, a thing held, a variable, an event), variable (a quantity, state or choice the story established matters from here on and nothing tracked fits: a debt, a health, a reputation). Not valid: colour, atmosphere, filling a quiet scene, something mentioned in passing, a passer-by or a crowd, scenery, or anything an existing character, place or thing can serve; use those. Ordinary things go through introduce_thing. A world author decides, and may decline and say what exists that can serve. A few things at most per turn.",
2585
- parameters: {
2586
- need: {
2587
- type: "string",
2588
- required: true,
2589
- enum: AUTHORING_NEEDS,
2590
- description: "Why: scene_change, arrival, introduction, object, variable or trigger."
2591
- },
2592
- what: {
2593
- type: "string",
2594
- required: true,
2595
- description: "What is needed, from what the story has established: who or where (a name when it was given), their role, what happened to make it needed now, and where it is in relation to what exists."
2596
- }
2597
- },
2598
- output: {
2599
- schema: { type: "json" },
2600
- render: (_args, value) => [{
2601
- type: "text",
2602
- text: renderExpansion(value)
2603
- }]
2604
- },
2605
- isConcurrencySafe: () => false,
2606
- async execute(args, exec) {
2607
- const { owner } = ownerOf(exec.agent);
2608
- await deps.engine.settle(owner.chat, owner.turn);
2609
- return record(await deps.engine.expand(owner, {
2610
- need: args.need,
2611
- what: args.what
2612
- }, exec.signal));
2613
- }
2614
- });
2615
- const introduce = defineTool({
2616
- name: INTRODUCE_TOOL,
2617
- description: "Bring a thing into the story as a table's game master would: something the story is about to use or that the player can find, take or handle (a barricade, a tool, a note, a bottle, a key) and that does not exist yet. It is made at once, where you say: at a place (at, a place key; the player's place when you say nothing), in someone's hands (held_by, a character key) or inside a thing (inside, an item key). Afterwards it is a thing like any other: use its key in item_changes. Not for scenery nobody will touch (that is just part of the place), not for something important and complex enough to need a world author (use expand_world, reason object), and never for what exists already (list_items). A few things at most per turn.",
2618
- parameters: {
2619
- name: {
2620
- type: "string",
2621
- required: true,
2622
- description: "What it is called, as the story names it."
2623
- },
2624
- description: {
2625
- type: "string",
2626
- description: "One or two sentences: what it looks like, what it is made of, what state it is in."
2627
- },
2628
- quantity: {
2629
- type: "integer",
2630
- description: "How many, when it is a number of the same thing (default 1)."
2631
- },
2632
- quality: {
2633
- type: "string",
2634
- description: "Its condition in a word or two (rusty, new), when that matters."
2635
- },
2636
- notable: {
2637
- type: "boolean",
2638
- description: "Whether the characters present would notice it at once."
2639
- },
2640
- hidden: {
2641
- type: "boolean",
2642
- description: "Whether it starts out of sight (until a round reveals it)."
2643
- },
2644
- at: {
2645
- type: "string",
2646
- description: "The key of the place it lies in."
2647
- },
2648
- held_by: {
2649
- type: "string",
2650
- description: "The key of the character who holds it."
2651
- },
2652
- inside: {
2653
- type: "string",
2654
- description: "The key of the container it is in."
2655
- }
2656
- },
2657
- output: {
2658
- schema: { type: "json" },
2659
- render: (_args, value) => {
2660
- const made = value;
2661
- return [{
2662
- type: "text",
2663
- text: `Introduced ${made.name} [${made.key}], ${made.where}. Use the key in item_changes; nobody has taken it up yet.`
2664
- }];
2665
- }
2666
- },
2667
- isConcurrencySafe: () => false,
2668
- async execute(args, exec) {
2669
- const { owner } = ownerOf(exec.agent);
2670
- await deps.engine.settle(owner.chat, owner.turn);
2671
- return record(deps.engine.introduce(owner, {
2672
- name: args.name,
2673
- ...args.description === void 0 ? {} : { description: args.description },
2674
- ...args.quantity === void 0 ? {} : { quantity: args.quantity },
2675
- ...args.quality === void 0 ? {} : { quality: args.quality },
2676
- ...args.notable === void 0 ? {} : { notable: args.notable },
2677
- ...args.hidden === void 0 ? {} : { hidden: args.hidden },
2678
- ...args.at === void 0 ? {} : { at: args.at },
2679
- ...args.held_by === void 0 ? {} : { heldBy: args.held_by },
2680
- ...args.inside === void 0 ? {} : { inside: args.inside }
2681
- }));
2682
- }
2683
- });
2684
- const skip = defineTool({
2685
- name: TIME_TOOL,
2686
- 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.",
2687
- parameters: {
2688
- reason: {
2689
- type: "string",
2690
- required: true,
2691
- description: "What happens in the time that passes, in a sentence (\"they sleep\", \"the ferry crosses\")."
2692
- },
2693
- by_minutes: {
2694
- type: "integer",
2695
- description: "How many minutes to skip."
2696
- },
2697
- until_time: {
2698
- type: "string",
2699
- description: "The time of day to skip to, 24-hour HH:MM: the next time the clock reads it, or the day given by days_later."
2700
- },
2701
- days_later: {
2702
- type: "integer",
2703
- description: "With until_time: that many days after today (0 is later today, 1 is tomorrow)."
2704
- }
2705
- },
2706
- output: {
2707
- schema: { type: "json" },
2708
- render: (_args, value) => {
2709
- const done = value;
2710
- return [{
2711
- type: "text",
2712
- text: `${describeDuration(done.to - done.from)} pass. It is now ${describeTime({
2713
- now: done.to,
2714
- zone: done.zone
2715
- })}.${done.moved.length === 0 ? "" : ` ${done.moved.map(routineLine).join(" ")}`} Nothing else changed: characters with you are still doing what they were, where they were; run a round for them if the time that passed changes that.${done.world.length === 0 ? "" : `\n${renderWorld(done.world).join("\n")}`}`
2716
- }];
2717
- }
2718
- },
2719
- isConcurrencySafe: () => false,
2720
- async execute(args, exec) {
2721
- const { owner } = ownerOf(exec.agent);
2722
- await deps.engine.settle(owner.chat, owner.turn);
2723
- if ([args.by_minutes !== void 0, args.until_time !== void 0].filter(Boolean).length !== 1) throw new Error("give exactly one of by_minutes and until_time");
2724
- if (args.days_later !== void 0 && args.until_time === void 0) throw new Error("days_later goes with until_time");
2725
- const request = args.by_minutes !== void 0 ? {
2726
- byMinutes: args.by_minutes,
2727
- reason: args.reason
2728
- } : {
2729
- untilTime: args.until_time ?? "",
2730
- ...args.days_later === void 0 ? {} : { daysLater: args.days_later },
2731
- reason: args.reason
2732
- };
2733
- return record(deps.engine.advanceTime(owner, request));
2734
- }
2735
- });
2736
- const preview = defineTool({
2737
- name: PREVIEW_TOOL,
2738
- description: "Show the player how the scene opens, as your very first action of a turn, before you ask any character: two or three sentences that set the mood and what the player's character perceives, ending on the open question of the moment. It is on screen at once, while the characters are still being asked, and is replaced in the player's view by the output you deliver with narrate, which may use it, change it or start over. Describe only what the scene and the player's own action establish: never what any other character does, says, decides or thinks, and nothing the player's character cannot perceive. Once per message.",
2739
- parameters: { text: {
2740
- type: "string",
2741
- required: true,
2742
- description: "The opening, plain prose in the narration voice."
2743
- } },
2744
- output: {
2745
- schema: { type: "json" },
2746
- render: (_args, value) => [{
2747
- type: "text",
2748
- text: `${encodePreview(value.text)}\nShown to the player. Now call activate_characters.`
2749
- }]
2750
- },
2751
- isConcurrencySafe: () => false,
2752
- execute(args, exec) {
2753
- const { owner } = ownerOf(exec.agent);
2754
- return Promise.resolve(record({ text: deps.engine.preview(owner, args.text) }));
2755
- }
2756
- });
2757
- const ruling = defineTool({
2758
- name: RULING_TOOL,
2759
- description: "Rule on the player's out-of-character command, as the very first thing of an out-of-character turn: legal is false only when the command breaks the rules of the world or the player's own rules (the scene lists them); what is merely strange, impossible for the characters, or hard on them is legal, because the player may change the story itself. The reason is shown to the player, so write it plainly to them. Only a legal ruling lets you change anything.",
2760
- parameters: {
2761
- rule_check: {
2762
- type: "string",
2763
- required: true,
2764
- description: "First, go through every rule the scene lists, one by one, in a few words each: does the command need what the rule excludes (the rules are literal: a rule against magic is broken by anything magical, however the command words it, and strange is not the same as against a rule)? Write \"no rules listed\" when there are none."
2765
- },
2766
- legal: {
2767
- type: "boolean",
2768
- required: true,
2769
- description: "Whether the command is allowed: false when any listed rule is broken."
2770
- },
2771
- reason: {
2772
- type: "string",
2773
- required: true,
2774
- description: "To the player, in plain words and briefly: what you will do, or which rule it breaks."
2775
- }
2776
- },
2777
- output: {
2778
- schema: { type: "json" },
2779
- render: (_args, value) => [{
2780
- type: "text",
2781
- text: value.legal ? `Ruled legal. Now make it happen: ${RESOLVE_TOOL} (outcomes for any characters, asked or not, with their moves and things), ${EXPAND_TOOL} (for what does not exist yet), ${TIME_TOOL}; do only what the command says. Then call ${NARRATE_TOOL} with narration only, of what the player can perceive.` : `Ruled illegal; nothing changes. Call ${NARRATE_TOOL} with no segments: the player is told why.`
2782
- }]
2783
- },
2784
- isConcurrencySafe: () => false,
2785
- execute(args, exec) {
2786
- const { owner } = ownerOf(exec.agent);
2787
- return Promise.resolve(record(deps.engine.rule(owner, args.legal, args.reason)));
2788
- }
2789
- });
2790
- const answer = defineTool({
2791
- name: ANSWER_TOOL,
2792
- 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.",
2793
- parameters: {},
2794
- output: {
2795
- schema: { type: "json" },
2796
- render: () => [{
2797
- type: "text",
2798
- text: `The player is shown the answer. Now call ${NARRATE_TOOL} with no segments.`
2799
- }]
2800
- },
2801
- isConcurrencySafe: () => false,
2802
- async execute(_args, exec) {
2803
- const { agent, owner } = ownerOf(exec.agent);
2804
- return record(await deps.engine.answer(owner, answerRunner({
2805
- parent: agent,
2806
- boundaries: deps.boundaries,
2807
- store: storeOf(owner.chat)
2808
- }), exec.signal));
2809
- }
2810
- });
2811
- return [
2812
- defineTool({
2813
- name: JUDGE_TOOL,
2814
- description: "Judge what the player's character tries, as the very first thing of an ordinary turn (nothing else is accepted before it): allowed is false when it is not viable (what it needs is out of reach, is not there, or the character cannot do it or does not have it) or when it breaks a rule of the world or of the player (the scene lists them and they are absolute: no magic means no spell works). The player's claim of an effect is not a fact. What merely looks strange, rash or foolish is allowed. When it is not allowed the attempt is played as a failure for the player's character, and nobody is asked to act on it.",
2815
- parameters: {
2816
- rule_check: {
2817
- type: "string",
2818
- required: true,
2819
- 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."
2820
- },
2821
- at: {
2822
- type: "string",
2823
- 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)."
2824
- },
2825
- allowed: {
2826
- type: "boolean",
2827
- required: true,
2828
- description: "Whether what the character tries can work: false when any listed rule is broken or it is not viable."
2829
- },
2830
- reason: {
2831
- type: "string",
2832
- required: true,
2833
- description: "What the character tries, and the rule or the fact that decides it, in a sentence."
2834
- }
2835
- },
2836
- output: {
2837
- schema: { type: "json" },
2838
- render: (_args, value) => [{
2839
- type: "text",
2840
- 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.`
2841
- }]
2842
- },
2843
- isConcurrencySafe: () => false,
2844
- execute(args, exec) {
2845
- const { owner } = ownerOf(exec.agent);
2846
- return Promise.resolve(record(deps.engine.judge(owner, args.allowed, args.reason, args.at)));
2847
- }
2848
- }),
2849
- preview,
2850
- ruling,
2851
- answer,
2852
- activate,
2853
- resolve,
2854
- skip,
2855
- remember,
2856
- expand,
2857
- introduce,
2858
- makePlot,
2859
- plot,
2860
- narrate
2861
- ];
2862
- }
2863
- //#endregion
2864
- //#region src/host/memory/embedding-index.ts
2865
- const BATCH = 32;
2866
- /**
2867
- * Keeps the vectors of a chat's texts: embeds what has none yet, and gives the vector of a moment to
2868
- * search with. The story knows which texts wait and keeps the vectors; this is the only part that
2869
- * talks to an embedding service. Everything degrades to searching by words: without a service, a
2870
- * provider that fails, or vectors made by another model than the one now selected, the search
2871
- * simply has no vector to use.
2872
- */
2873
- var EmbeddingIndex = class {
2874
- deps;
2875
- running = /* @__PURE__ */ new Map();
2876
- reported = /* @__PURE__ */ new Set();
2877
- constructor(deps) {
2878
- this.deps = deps;
2879
- }
2880
- /** Embed what is waiting, in the background; calls for one chat run one after another. */
2881
- schedule(chat) {
2882
- const next = (this.running.get(chat) ?? Promise.resolve()).then(() => this.fill(chat)).catch((error) => {
2883
- this.complain(`indexing ${chat}`, error);
979
+ var EmbeddingIndex = class {
980
+ deps;
981
+ running = /* @__PURE__ */ new Map();
982
+ reported = /* @__PURE__ */ new Set();
983
+ constructor(deps) {
984
+ this.deps = deps;
985
+ }
986
+ /** Embed what is waiting, in the background; calls for one chat run one after another. */
987
+ schedule(chat) {
988
+ const next = (this.running.get(chat) ?? Promise.resolve()).then(() => this.fill(chat)).catch((error) => {
989
+ this.complain(`indexing ${chat}`, error);
2884
990
  });
2885
991
  this.running.set(chat, next);
2886
992
  next.finally(() => {
@@ -3096,154 +1202,6 @@ var AfterTurnJobs = class {
3096
1202
  }));
3097
1203
  }
3098
1204
  };
3099
- /**
3100
- * What the characters away from the player decide about what fell due, one commitment after another: their activity, and a move to where the commitment was when they
3101
- * mean to keep it. It is recorded as a round only they perceive, and the keeper writes it.
3102
- */
3103
- async function runOffScene(deps, owner, state, store, due, limit) {
3104
- const { summary, perCharacter, joint } = store.settings().offstage;
3105
- let budget = limit;
3106
- const acted = /* @__PURE__ */ new Map();
3107
- for (const item of due) {
3108
- if (budget <= 0) break;
3109
- const cast = store.cast();
3110
- const keys = item.characters.filter((key) => cast.some((member) => member.key === key) && (acted.get(key) ?? 0) < perCharacter).slice(0, budget);
3111
- if (keys.length === 0) continue;
3112
- budget -= keys.length;
3113
- for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
3114
- const reports = [];
3115
- for (const group of joint ? keys.map((key) => [key]) : [keys]) {
3116
- const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
3117
- const asked = {
3118
- ...state,
3119
- situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
3120
- history: [],
3121
- recalled: /* @__PURE__ */ new Map()
3122
- };
3123
- delete asked.first;
3124
- delete asked.second;
3125
- reports.push(...(await deps.ask(group, cast, asked, summary)).reports);
3126
- }
3127
- if (reports.length === 0) continue;
3128
- const where = item.place;
3129
- const moves = new Map(reports.flatMap((report) => {
3130
- if (report.commitment === "low" || where === void 0) return [];
3131
- const check = store.checkMove(report.character, {
3132
- location: where,
3133
- ignoreExits: true
3134
- });
3135
- return check.ok ? [[report.character, check]] : [];
3136
- }));
3137
- store.commit(reports.flatMap((report) => {
3138
- const member = cast.find((candidate) => candidate.key === report.character);
3139
- const move = moves.get(report.character);
3140
- return member === void 0 ? [] : [{
3141
- character: member.character.id,
3142
- patch: { activity: report.intent },
3143
- ...move?.ok === true ? { move: move.move } : {}
3144
- }];
3145
- }));
3146
- state.offstage += 1;
3147
- const time = store.time(owner.turn);
3148
- store.queueCommit({
3149
- turn: owner.turn,
3150
- round: 100 + state.offstage,
3151
- situation: item.text,
3152
- offstage: true,
3153
- time: {
3154
- from: time.now,
3155
- to: time.now,
3156
- zone: time.zone
3157
- },
3158
- entries: reports.map((report) => {
3159
- const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
3160
- const move = moves.get(report.character);
3161
- return {
3162
- character: report.character,
3163
- name: report.name,
3164
- intent: report.intent,
3165
- commitment: report.commitment,
3166
- result: "succeeded",
3167
- summary: report.intent,
3168
- spoken: false,
3169
- ...at === void 0 ? {} : { at: {
3170
- key: locationKey(at),
3171
- name: at.name
3172
- } },
3173
- ...move?.ok === true && move.plan.from !== move.move.to ? { moved: { ...move.to } } : {}
3174
- };
3175
- })
3176
- });
3177
- store.markHandled([item.key]);
3178
- deps.write();
3179
- if (summary && deps.stillThis()) {
3180
- const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
3181
- store.addNote("away", owner.turn, lines);
3182
- }
3183
- }
3184
- }
3185
- //#endregion
3186
- //#region src/host/orchestration/turn-text.ts
3187
- /**
3188
- * A model sometimes sends who speaks as a segment of its own (an utterance with no character whose text is the character's key or name) followed by the words with no
3189
- * character either. When the label is exactly a character of the scene, the label is folded into the words that follow it.
3190
- */
3191
- function foldSpeakerLabels(segments, cast) {
3192
- const found = (label) => {
3193
- const wanted = label.trim().normalize("NFKC").toLowerCase();
3194
- return wanted === "" ? void 0 : cast.find((member) => member.key.toLowerCase() === wanted || member.character.name.normalize("NFKC").toLowerCase() === wanted);
3195
- };
3196
- const folded = [];
3197
- for (let index = 0; index < segments.length; index += 1) {
3198
- const segment = segments[index];
3199
- const next = segments[index + 1];
3200
- const speaker = segment.type === "utterance" && (segment.character ?? "") === "" && next?.type === "utterance" && (next.character ?? "") === "" ? found(segment.text) : void 0;
3201
- if (speaker === void 0) {
3202
- folded.push(segment);
3203
- continue;
3204
- }
3205
- folded.push({
3206
- ...next,
3207
- character: speaker.key
3208
- });
3209
- index += 1;
3210
- }
3211
- return folded;
3212
- }
3213
- /** 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. */
3214
- const SAME_SITUATION = .85;
3215
- const pieces = (text) => {
3216
- const found = /* @__PURE__ */ new Set();
3217
- const chars = [...text];
3218
- for (let index = 0; index + 3 <= chars.length; index += 1) found.add(chars.slice(index, index + 3).join(""));
3219
- return found;
3220
- };
3221
- /** 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. */
3222
- function repeatsEarlier(signature, asked) {
3223
- const [keys = "", text = ""] = signature.split("|");
3224
- const now = new Set(keys.split(","));
3225
- const mine = pieces(text);
3226
- return asked.some((earlier) => {
3227
- const [before = "", was = ""] = earlier.split("|");
3228
- if (![...now].every((key) => before.split(",").includes(key))) return false;
3229
- const theirs = pieces(was);
3230
- const shared = [...mine].filter((piece) => theirs.has(piece)).length;
3231
- const union = mine.size + theirs.size - shared;
3232
- return union === 0 || shared / union >= SAME_SITUATION;
3233
- });
3234
- }
3235
- /** The words as the character said them, whatever quotes the game master put around them. */
3236
- function asSpoken(segments, spoken) {
3237
- const left = [...spoken];
3238
- return segments.map((segment) => {
3239
- if (segment.type !== "utterance") return segment;
3240
- const at = left.findIndex((said) => said.character === segment.character && sameWords(said.text, segment.text));
3241
- return at === -1 ? segment : {
3242
- ...segment,
3243
- text: left.splice(at, 1)[0].text
3244
- };
3245
- });
3246
- }
3247
1205
  //#endregion
3248
1206
  //#region src/host/orchestration/turn-rules.ts
3249
1207
  /** Whether the game master still has to judge the player's action. */
@@ -3261,6 +1219,11 @@ function oocBlock(state) {
3261
1219
  function previewDue(state) {
3262
1220
  return state.phase === "idle" && state.previewWanted && !state.previewed && state.judgement?.allowed !== false;
3263
1221
  }
1222
+ /** Whether the game master still has to roll for an attempt it judged uncertain: nobody is asked to act before the dice are rolled. */
1223
+ function rollDue(state, store) {
1224
+ return state.rollWanted === true && state.phase === "idle" && state.judgement?.allowed !== false && store.story.dice.rolls({ turn: state.turn }).every((roll) => roll.by !== "agent");
1225
+ }
1226
+ const ROLL_FIRST = "the attempt is uncertain and matters, so roll for it before anyone is asked to act: call roll_check with the check that fits (list_checks shows them), naming the character it is for; roll_dice only when no check fits";
3264
1227
  function explainPhase(state, attempted) {
3265
1228
  if (state.ooc?.question === true && (state.phase === "idle" || state.phase === "between")) return state.ooc.ruling === void 0 ? "this turn is an out-of-character question: answer it first with ooc_answer" : "a question changes nothing: call narrate with no segments";
3266
1229
  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";
@@ -3282,7 +1245,7 @@ function mustSay(state) {
3282
1245
  return state.utterances.length === 0 ? "" : `; it must carry these utterances exactly, in this order: ${state.utterances.map((utterance) => `${utterance.name}: "${utterance.text}"`).join(" | ")}`;
3283
1246
  }
3284
1247
  /** `player` is the key of the player's character when an outcome for it is acceptable: it is not asked to act, but what it did can move it or have it handle things. */
3285
- function checkOutcomes(attempt, outcomes, store, player, decreed) {
1248
+ function checkOutcomes(attempt, outcomes, store, player, decreed, state) {
3286
1249
  const expected = decreed === void 0 ? attempt.reports.map((report) => report.character) : [...new Set(outcomes.map((outcome) => outcome.character))];
3287
1250
  const unknown = decreed === void 0 ? [] : [...new Set(outcomes.map((outcome) => outcome.character))].filter((key) => !decreed.some((member) => member.key === key)).map((key) => `${key} is not a character of the story`);
3288
1251
  const given = outcomes.filter((outcome) => outcome.character !== player).map((outcome) => outcome.character);
@@ -3296,9 +1259,35 @@ function checkOutcomes(attempt, outcomes, store, player, decreed) {
3296
1259
  ...outcomes.filter((outcome) => outcome.summary.trim() === "").map((outcome) => `${outcome.character}: say what happens`),
3297
1260
  ...outcomes.flatMap((outcome) => moveProblems(outcome, store)),
3298
1261
  ...itemProblems(outcomes, store),
3299
- ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`))
1262
+ ...outcomes.flatMap((outcome) => store.checkVariableChanges(outcome.variableChanges ?? []).map((problem) => `${outcome.character}: ${problem}`)),
1263
+ ...state === void 0 ? [] : rollProblems(outcomes, store, state)
3300
1264
  ];
3301
1265
  if (problems.length > 0) throw new Error(`the outcomes are not acceptable: ${problems.join("; ")} (expected exactly: ${expected.join(", ")})`);
1266
+ for (const outcome of outcomes) if (outcome.roll !== void 0) state?.cited.add(outcome.roll);
1267
+ }
1268
+ /**
1269
+ * Why an outcome does not follow the dice, if it does not. A roll decides what it was rolled for: the result of the outcome is the roll's own, a roll serves one outcome,
1270
+ * and a character a check was rolled for cannot be given an outcome without it.
1271
+ */
1272
+ function rollProblems(outcomes, store, state) {
1273
+ const rolls = store.story.dice.rolls({ turn: state.turn });
1274
+ const problems = [];
1275
+ const taken = /* @__PURE__ */ new Set();
1276
+ for (const outcome of outcomes) {
1277
+ if (outcome.roll === void 0) continue;
1278
+ const roll = rolls.find((candidate) => candidate.id === outcome.roll);
1279
+ if (roll === void 0) problems.push(`${outcome.character}: there is no roll ${outcome.roll} in this turn: use the id the roll tool gave`);
1280
+ else if (roll.readout === void 0) problems.push(`${outcome.character}: roll ${roll.id} was a plain roll with no result to take: leave roll out and decide it yourself`);
1281
+ else if (state.cited.has(roll.id) || taken.has(roll.id)) problems.push(`${outcome.character}: roll ${roll.id} already decided another outcome: roll again for this one`);
1282
+ else if (roll.character !== void 0 && roll.character !== outcome.character) problems.push(`${outcome.character}: roll ${roll.id} was for ${roll.character}`);
1283
+ else if (roll.readout.result !== outcome.result) problems.push(`${outcome.character}: roll ${roll.id} gave ${roll.readout.result} (${roll.readout.label}), so the outcome's result is ${roll.readout.result}, not ${outcome.result}: the dice decide it`);
1284
+ taken.add(outcome.roll);
1285
+ }
1286
+ for (const roll of rolls) {
1287
+ if (roll.readout === void 0 || roll.character === void 0 || state.cited.has(roll.id) || taken.has(roll.id)) continue;
1288
+ if (outcomes.some((outcome) => outcome.character === roll.character && outcome.roll === void 0)) problems.push(`${roll.character}: you rolled for this character (roll ${roll.id}: ${roll.readout.label}, ${roll.readout.result}): give the outcome the result ${roll.readout.result} and cite the roll by adding "roll": ${roll.id} to that outcome`);
1289
+ }
1290
+ return problems;
3302
1291
  }
3303
1292
  /** Why a character cannot go where the outcome sends it, if it cannot: the game master hears it before the round is recorded. */
3304
1293
  function moveProblems(outcome, store) {
@@ -3347,49 +1336,581 @@ function knownRelationships(member, company, situation, cast, store) {
3347
1336
  }];
3348
1337
  });
3349
1338
  }
3350
- function reactions(state) {
3351
- const first = state.first;
3352
- return (first?.outcomes ?? []).flatMap((outcome) => {
3353
- const report = first?.reports.find((candidate) => candidate.character === outcome.character);
3354
- return report === void 0 ? [] : [{
3355
- character: report.character,
3356
- name: report.name,
3357
- intent: report.intent,
3358
- ...report.utterance === void 0 ? {} : { utterance: report.utterance },
3359
- result: outcome.result,
3360
- summary: outcome.summary
3361
- }];
1339
+ function reactions(state) {
1340
+ const first = state.first;
1341
+ return (first?.outcomes ?? []).flatMap((outcome) => {
1342
+ const report = first?.reports.find((candidate) => candidate.character === outcome.character);
1343
+ return report === void 0 ? [] : [{
1344
+ character: report.character,
1345
+ name: report.name,
1346
+ intent: report.intent,
1347
+ ...report.utterance === void 0 ? {} : { utterance: report.utterance },
1348
+ result: outcome.result,
1349
+ summary: outcome.summary
1350
+ }];
1351
+ });
1352
+ }
1353
+ /** The final decision for each character of the round: the retry's replaces the first attempt's. */
1354
+ /** The player's character is never asked to act, so what the game master decided it did stands in for its report. */
1355
+ function playerReport(state, outcome) {
1356
+ const member = state.cast.find((candidate) => candidate.key === outcome.character && candidate.character.control === "player");
1357
+ return member === void 0 ? void 0 : {
1358
+ character: member.key,
1359
+ name: member.character.name,
1360
+ intent: outcome.summary,
1361
+ commitment: "high"
1362
+ };
1363
+ }
1364
+ function decisions(state) {
1365
+ const decided = /* @__PURE__ */ new Map();
1366
+ for (const attempt of [state.first, state.second]) for (const outcome of attempt?.outcomes ?? []) {
1367
+ const report = attempt?.reports.find((candidate) => candidate.character === outcome.character) ?? playerReport(state, outcome);
1368
+ if (report !== void 0) decided.set(outcome.character, {
1369
+ outcome,
1370
+ report
1371
+ });
1372
+ }
1373
+ return decided;
1374
+ }
1375
+ //#endregion
1376
+ //#region src/host/orchestration/character-attempt.ts
1377
+ /** Every character acts at the same time; one that fails or answers badly is reported, not fatal. */
1378
+ async function askCharacters(deps, owner, number, keys, cast, state, run, signal, away = false) {
1379
+ const { store, boundaries } = deps;
1380
+ const { outputValidator } = boundaries;
1381
+ const reaction = number === 2 ? reactions(state) : void 0;
1382
+ const queryVector = number === 1 && store !== void 0 ? await store.queryVector(state.situation, signal) : void 0;
1383
+ const time = store?.time(owner.turn);
1384
+ const answers = await Promise.all(keys.map(async (key) => {
1385
+ const member = cast.find((candidate) => candidate.key === key);
1386
+ if (member === void 0) return {
1387
+ character: key,
1388
+ name: key,
1389
+ reason: "no such character"
1390
+ };
1391
+ const previous = number === 2 ? state.first?.reports.find((report) => report.character === key) : void 0;
1392
+ const memories = number === 1 && store !== void 0 ? await boundaries.recaller.recall({
1393
+ member,
1394
+ situation: state.situation,
1395
+ turn: owner.turn,
1396
+ policy: store.settings().memory,
1397
+ ...store.settings().diagnostics.keepRuns ? { explain: true } : {},
1398
+ ...queryVector === void 0 ? {} : { queryVector }
1399
+ }, store.story, signal) : state.recalled.get(key) ?? [];
1400
+ if (number === 1 && memories.length > 0) state.recalled.set(key, memories);
1401
+ const place = member.place === void 0 ? void 0 : store?.place(member.place.location.id);
1402
+ const relationships = store === void 0 ? [] : knownRelationships(member, place === void 0 ? cast : place.here, state.situation, cast, store);
1403
+ const carrying = store === void 0 ? [] : store.carried(member.character.id);
1404
+ const knowledge = store?.knowledge(member.character.id, owner.turn, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
1405
+ const affiliations = store?.affiliations(member.character.id) ?? [];
1406
+ const agenda = store?.agenda(owner.turn, member.character.id);
1407
+ const cues = cuesOf(state, key, member, store, number);
1408
+ const upcoming = store?.upcomingFor(member.character.id, owner.turn) ?? [];
1409
+ const tracked = store?.trackedFor(member.character.id, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
1410
+ const request = {
1411
+ member,
1412
+ cast,
1413
+ situation: state.situation,
1414
+ attempt: number,
1415
+ language: store?.settings().prompts.language ?? "en",
1416
+ turn: owner.turn,
1417
+ ...away ? { away: true } : {},
1418
+ lookup: store === void 0 ? false : store.settings().memory.lookup && toolEnabled(store.settings().tools, "characters", "recall_my_memories"),
1419
+ text: (id, variables) => deps.storeOf(owner).text(id, variables),
1420
+ ...time === void 0 ? {} : { time },
1421
+ ...agenda === void 0 ? {} : { agenda },
1422
+ ...cues.length === 0 ? {} : { cues },
1423
+ ...upcoming.length === 0 ? {} : { upcoming },
1424
+ ...tracked === void 0 || tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
1425
+ ...place === void 0 ? {} : { place },
1426
+ ...relationships.length === 0 ? {} : { relationships },
1427
+ ...carrying.length === 0 ? {} : { carrying },
1428
+ ...knowledge === void 0 ? {} : { knowledge },
1429
+ ...affiliations.length === 0 ? {} : { affiliations },
1430
+ ...memories.length === 0 ? {} : { memories },
1431
+ ...state.history.length === 0 ? {} : { earlier: [...state.history] },
1432
+ ...reaction === void 0 ? {} : { reaction },
1433
+ ...previous === void 0 ? {} : { previous: {
1434
+ intent: previous.intent,
1435
+ commitment: previous.commitment
1436
+ } }
1437
+ };
1438
+ try {
1439
+ const action = await run(request, signal);
1440
+ const verdict = outputValidator.validate(action, request);
1441
+ if (!verdict.ok) return {
1442
+ character: key,
1443
+ name: member.character.name,
1444
+ reason: verdict.reason
1445
+ };
1446
+ return {
1447
+ character: key,
1448
+ name: member.character.name,
1449
+ ...action
1450
+ };
1451
+ } catch (error) {
1452
+ if (signal.aborted) throw error;
1453
+ const reason = error instanceof Error ? error.message : String(error);
1454
+ deps.problem(`${member.character.name} could not act: ${reason}`);
1455
+ return {
1456
+ character: key,
1457
+ name: member.character.name,
1458
+ reason,
1459
+ technical: true
1460
+ };
1461
+ }
1462
+ }));
1463
+ return {
1464
+ reports: answers.filter((answer) => "intent" in answer),
1465
+ failures: answers.filter((answer) => "reason" in answer)
1466
+ };
1467
+ }
1468
+ //#endregion
1469
+ //#region src/host/orchestration/round-record.ts
1470
+ /** Records the game master's decisions as a finished round: what the characters did and said, what changed in the story, and the round queued for the keeper. `fire` runs the triggers the round may have made true. */
1471
+ function recordRound(store, owner, state, fire) {
1472
+ const decided = decisions(state);
1473
+ const limit = store.settings().maxRounds;
1474
+ const round = state.rounds + 1;
1475
+ const checked = new Map([...decided.values()].flatMap(({ outcome }) => outcome.moveTo === void 0 ? [] : [[outcome.character, store.checkMove(outcome.character, outcome.moveTo)]]));
1476
+ const refused = [...checked].flatMap(([character, check]) => check.ok ? [] : [`${character}: ${check.problems.join("; ")}`]);
1477
+ if (refused.length > 0) throw new Error(`a move is no longer possible: ${refused.join("; ")}`);
1478
+ const spoken = [...decided.values()].flatMap(({ outcome, report }) => report.utterance === void 0 || outcome.spoken === false || state.utterances.some((said) => said.character === report.character && sameWords(said.text, report.utterance)) ? [] : [{
1479
+ character: report.character,
1480
+ name: report.name,
1481
+ text: report.utterance,
1482
+ round
1483
+ }]);
1484
+ state.rounds = round;
1485
+ state.situations.push(state.situation);
1486
+ state.utterances.push(...spoken);
1487
+ for (const { outcome, report } of decided.values()) {
1488
+ state.reports.push(report);
1489
+ state.outcomes.push(outcome);
1490
+ state.history.push({
1491
+ round,
1492
+ character: report.character,
1493
+ name: report.name,
1494
+ intent: report.intent,
1495
+ ...report.utterance === void 0 ? {} : { utterance: report.utterance },
1496
+ result: outcome.result,
1497
+ summary: outcome.summary
1498
+ });
1499
+ }
1500
+ state.limit = limit;
1501
+ state.phase = "between";
1502
+ const playerPlace = state.cast.find((member) => member.character.control === "player")?.place?.location;
1503
+ const updates = [...decided.values()].flatMap(({ outcome, report }) => {
1504
+ const member = state.cast.find((candidate) => candidate.key === report.character);
1505
+ if (member === void 0) return [];
1506
+ const check = checked.get(outcome.character);
1507
+ return [{
1508
+ key: report.character,
1509
+ update: {
1510
+ character: member.character.id,
1511
+ patch: {
1512
+ activity: outcome.summary,
1513
+ ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() }
1514
+ },
1515
+ ...check?.ok === true ? { move: check.move } : {},
1516
+ ...outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 ? {} : { items: outcome.itemChanges }
1517
+ }
1518
+ }];
1519
+ });
1520
+ const effects = /* @__PURE__ */ new Map();
1521
+ const done = store.commit(updates.map((entry) => entry.update));
1522
+ updates.forEach(({ key }, index) => {
1523
+ effects.set(key, done[index] ?? []);
1524
+ });
1525
+ const tracked = new Map(updates.map(({ key }) => [key, store.changeVariables(owner.turn, decided.get(key)?.outcome.variableChanges ?? []).map((effect) => ({
1526
+ subject: effect.subjectName,
1527
+ name: effect.variable.name,
1528
+ from: describeValue(effect.variable, effect.from),
1529
+ to: describeValue(effect.variable, effect.to)
1530
+ }))]));
1531
+ const journey = [...checked].flatMap(([character, check]) => check.ok && state.cast.find((candidate) => candidate.key === character)?.character.control === "player" ? [check.plan.travelSeconds ?? 0] : [])[0];
1532
+ const time = store.endRound(owner.turn, round, state.elapsed, journey);
1533
+ delete state.elapsed;
1534
+ const world = fire(round);
1535
+ const loose = store.story.dice.rolls({ turn: owner.turn }).filter((roll) => !state.cited.has(roll.id) && !state.reported.has(roll.id));
1536
+ for (const roll of loose) state.reported.add(roll.id);
1537
+ store.queueCommit({
1538
+ turn: owner.turn,
1539
+ round,
1540
+ situation: state.situation,
1541
+ ...loose.length === 0 ? {} : { rolls: loose.map((roll) => `${roll.reason}: ${roll.expression} came to ${roll.total}${roll.readout === void 0 ? "" : `: ${roll.readout.label}${roll.readout.critical ? " (critical)" : ""} (${roll.readout.result})`}${roll.by === "player" ? " (rolled by the player)" : ""}`) },
1542
+ ...playerPlace === void 0 ? {} : { place: {
1543
+ key: locationKey(playerPlace),
1544
+ name: playerPlace.name
1545
+ } },
1546
+ time: {
1547
+ from: time.from,
1548
+ to: time.to,
1549
+ zone: time.zone
1550
+ },
1551
+ entries: [...decided.values()].map(({ outcome, report }) => {
1552
+ const at = state.cast.find((candidate) => candidate.key === report.character)?.place?.location;
1553
+ const check = checked.get(outcome.character);
1554
+ return {
1555
+ character: report.character,
1556
+ name: report.name,
1557
+ intent: report.intent,
1558
+ commitment: report.commitment,
1559
+ ...report.utterance === void 0 ? {} : { utterance: report.utterance },
1560
+ result: outcome.result,
1561
+ summary: outcome.summary,
1562
+ ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() },
1563
+ spoken: outcome.spoken !== false,
1564
+ ...(tracked.get(report.character) ?? []).length === 0 ? {} : { variables: tracked.get(report.character) },
1565
+ ...state.cast.find((candidate) => candidate.key === report.character)?.character.control === "player" ? { player: true } : {},
1566
+ ...report.forced === true ? { forced: true } : {},
1567
+ ...(effects.get(report.character) ?? []).length === 0 ? {} : { items: (effects.get(report.character) ?? []).map((effect) => ({
1568
+ name: effect.item.name,
1569
+ action: effect.action,
1570
+ summary: effect.summary
1571
+ })) },
1572
+ ...at === void 0 ? {} : { at: {
1573
+ key: locationKey(at),
1574
+ name: at.name
1575
+ } },
1576
+ ...check?.ok === true && check.plan.from !== check.move.to ? { moved: {
1577
+ ...check.to,
1578
+ ...check.position === void 0 ? {} : { position: check.position }
1579
+ } } : {}
1580
+ };
1581
+ })
1582
+ });
1583
+ return {
1584
+ round,
1585
+ limit,
1586
+ updated: [...decided.keys()],
1587
+ retryFailures: state.second?.failures ?? [],
1588
+ utterances: spoken,
1589
+ spoken: [...state.utterances],
1590
+ waiting: store.pendingCommits().length,
1591
+ variables: [...tracked.values()].flat().map((change) => `${change.subject}'s ${change.name} is now ${change.to} (it was ${change.from})`),
1592
+ time: {
1593
+ from: time.from,
1594
+ to: time.to,
1595
+ zone: time.zone
1596
+ },
1597
+ moved: time.moved,
1598
+ world,
1599
+ things: [...effects].flatMap(([character, list]) => list.map((effect) => ({
1600
+ character,
1601
+ name: effect.item.name,
1602
+ action: effect.action,
1603
+ summary: effect.summary
1604
+ }))),
1605
+ moves: [...checked].flatMap(([character, check]) => check.ok && check.plan.from !== check.move.to ? [{
1606
+ character,
1607
+ name: decided.get(character)?.report.name ?? character,
1608
+ to: check.to.name,
1609
+ via: Math.max(0, check.plan.via.length - 1)
1610
+ }] : [])
1611
+ };
1612
+ }
1613
+ //#endregion
1614
+ //#region src/host/orchestration/question-request.ts
1615
+ /** 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. */
1616
+ async function questionRequest(boundaries, store, owner, question, signal) {
1617
+ const cast = store.cast();
1618
+ const member = cast.find((candidate) => candidate.character.control === "player");
1619
+ if (member === void 0) throw new Error("there is no player's character to answer for");
1620
+ const queryVector = await store.queryVector(question, signal);
1621
+ const memories = await boundaries.recaller.recall({
1622
+ member,
1623
+ situation: question,
1624
+ turn: owner.turn,
1625
+ policy: store.settings().memory,
1626
+ ...queryVector === void 0 ? {} : { queryVector }
1627
+ }, store.story, signal);
1628
+ const place = member.place === void 0 ? void 0 : store.place(member.place.location.id);
1629
+ const company = place === void 0 ? cast : place.here;
1630
+ const relationships = knownRelationships(member, company, question, cast, store);
1631
+ const carrying = store.carried(member.character.id);
1632
+ const affiliations = store.affiliations(member.character.id);
1633
+ const tracked = store.trackedFor(member.character.id, company.map((entry) => entry.character.id));
1634
+ return {
1635
+ member,
1636
+ cast,
1637
+ situation: question,
1638
+ attempt: 1,
1639
+ language: store.settings().prompts.language,
1640
+ turn: owner.turn,
1641
+ lookup: false,
1642
+ text: (id, variables) => store.text(id, variables),
1643
+ time: store.time(owner.turn),
1644
+ knowledge: store.knowledge(member.character.id, owner.turn, company.map((entry) => entry.character.id)),
1645
+ ...tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
1646
+ ...place === void 0 ? {} : { place },
1647
+ ...relationships.length === 0 ? {} : { relationships },
1648
+ ...carrying.length === 0 ? {} : { carrying },
1649
+ ...affiliations.length === 0 ? {} : { affiliations },
1650
+ ...memories.length === 0 ? {} : { memories }
1651
+ };
1652
+ }
1653
+ //#endregion
1654
+ //#region src/host/orchestration/world-making.ts
1655
+ /**
1656
+ * The game master asks for something to be made up (a place the story has gone to, someone who has
1657
+ * joined): the world author decides whether the story genuinely needs it, and makes it or says why not.
1658
+ * The world may be closed, and only so many things may be made up in a turn.
1659
+ * @throws {Error} when the world is closed, the limit of the turn is reached, a round is open, or the request is empty.
1660
+ */
1661
+ async function expandWorld(boundaries, store, state, owner, input, signal) {
1662
+ if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: the world is extended between rounds, not in the middle of one");
1663
+ const blocked = oocBlock(state);
1664
+ if (blocked !== void 0) throw new Error(blocked);
1665
+ const need = AUTHORING_NEEDS.find((candidate) => candidate === input.need);
1666
+ if (need === void 0) throw new Error(`"${input.need}" is not a reason to make something up; the reasons are: ${AUTHORING_NEEDS.join(", ")}`);
1667
+ const what = input.what.trim();
1668
+ if (what === "") throw new Error("say what is needed, from what the story has established: who or where, and why now");
1669
+ const { authoring } = store.settings();
1670
+ if (!authoring.enabled) throw new Error("this world is closed: nothing can be made up in it");
1671
+ const made = store.story.consolidation.createdIn(owner.turn).length;
1672
+ if (made >= authoring.perTurn) throw new Error(`${made} new thing${made === 1 ? " was" : "s were"} already made up this turn, which is the most this chat allows: work with what exists`);
1673
+ return await boundaries.author.create({
1674
+ chat: owner.chat,
1675
+ turn: owner.turn,
1676
+ need,
1677
+ what,
1678
+ store
1679
+ }, signal);
1680
+ }
1681
+ /**
1682
+ * The game master introduces a thing the story uses, as a table's game master would: it is made at once where the game master says
1683
+ * (a place, someone's hands, a container; the player's place when it says nothing), with no world author asked.
1684
+ * @throws {Error} when the world is closed, a round is open, the turn's allowance is used, or the thing cannot be put where it was said.
1685
+ */
1686
+ function introduceThing(store, state, owner, input) {
1687
+ if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: things are introduced between rounds, not in the middle of one");
1688
+ const blocked = oocBlock(state);
1689
+ if (blocked !== void 0) throw new Error(blocked);
1690
+ const name = input.name.trim();
1691
+ if (name === "") throw new Error("name the thing");
1692
+ const { authoring } = store.settings();
1693
+ if (!authoring.enabled) throw new Error("this world is closed: nothing can be made up in it");
1694
+ const kept = store.story.consolidation.createdIn(owner.turn).filter((entry) => entry.kind === "item").length;
1695
+ if (kept >= authoring.thingsPerTurn) throw new Error(`${kept} thing${kept === 1 ? " was" : "s were"} already introduced this turn, which is the most this chat allows`);
1696
+ if ([
1697
+ input.at,
1698
+ input.heldBy,
1699
+ input.inside
1700
+ ].filter((entry) => entry !== void 0 && entry.trim() !== "").length > 1) throw new Error("say where it is in one way only: at a place, held by a character, or inside a thing");
1701
+ const here = store.cast().find((member) => member.character.control === "player")?.place?.location;
1702
+ const placed = input.heldBy !== void 0 && input.heldBy.trim() !== "" ? { heldBy: input.heldBy.trim() } : input.inside !== void 0 && input.inside.trim() !== "" ? { inside: input.inside.trim() } : input.at !== void 0 && input.at.trim() !== "" ? { at: { location: input.at.trim() } } : here === void 0 ? void 0 : { at: { location: locationKey(here) } };
1703
+ if (placed === void 0) throw new Error("say where it is: no place is known for the player, so name a place (at), a holder (held_by) or a container (inside)");
1704
+ const key = uniqueKey(slug(name, "thing"), new Set(store.story.items.list().map((item) => item.sourceId).filter((entry) => entry !== void 0)));
1705
+ store.story.edit({
1706
+ turn: owner.turn,
1707
+ items: [{
1708
+ key,
1709
+ name,
1710
+ ...input.description === void 0 || input.description.trim() === "" ? {} : { description: input.description.trim() },
1711
+ ...input.quantity === void 0 ? {} : { quantity: input.quantity },
1712
+ ...input.quality === void 0 || input.quality.trim() === "" ? {} : { quality: input.quality.trim() },
1713
+ ...input.notable === void 0 ? {} : { notable: input.notable },
1714
+ ...input.hidden === void 0 ? {} : { hidden: input.hidden },
1715
+ ...placed,
1716
+ note: "introduced by the game master"
1717
+ }]
1718
+ });
1719
+ return {
1720
+ key,
1721
+ name,
1722
+ where: "heldBy" in placed ? `held by ${placed.heldBy}` : "inside" in placed ? `inside ${placed.inside}` : `at ${placed.at.location}`
1723
+ };
1724
+ }
1725
+ //#endregion
1726
+ //#region src/host/orchestration/turn-text.ts
1727
+ /**
1728
+ * 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
1729
+ * character either. When the label is exactly a character of the scene, the label is folded into the words that follow it.
1730
+ */
1731
+ function foldSpeakerLabels(segments, cast) {
1732
+ const found = (label) => {
1733
+ const wanted = label.trim().normalize("NFKC").toLowerCase();
1734
+ return wanted === "" ? void 0 : cast.find((member) => member.key.toLowerCase() === wanted || member.character.name.normalize("NFKC").toLowerCase() === wanted);
1735
+ };
1736
+ const folded = [];
1737
+ for (let index = 0; index < segments.length; index += 1) {
1738
+ const segment = segments[index];
1739
+ const next = segments[index + 1];
1740
+ const speaker = segment.type === "utterance" && (segment.character ?? "") === "" && next?.type === "utterance" && (next.character ?? "") === "" ? found(segment.text) : void 0;
1741
+ if (speaker === void 0) {
1742
+ folded.push(segment);
1743
+ continue;
1744
+ }
1745
+ folded.push({
1746
+ ...next,
1747
+ character: speaker.key
1748
+ });
1749
+ index += 1;
1750
+ }
1751
+ return folded;
1752
+ }
1753
+ /** 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. */
1754
+ const SAME_SITUATION = .85;
1755
+ const pieces = (text) => {
1756
+ const found = /* @__PURE__ */ new Set();
1757
+ const chars = [...text];
1758
+ for (let index = 0; index + 3 <= chars.length; index += 1) found.add(chars.slice(index, index + 3).join(""));
1759
+ return found;
1760
+ };
1761
+ /** 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. */
1762
+ function repeatsEarlier(signature, asked) {
1763
+ const [keys = "", text = ""] = signature.split("|");
1764
+ const now = new Set(keys.split(","));
1765
+ const mine = pieces(text);
1766
+ return asked.some((earlier) => {
1767
+ const [before = "", was = ""] = earlier.split("|");
1768
+ if (![...now].every((key) => before.split(",").includes(key))) return false;
1769
+ const theirs = pieces(was);
1770
+ const shared = [...mine].filter((piece) => theirs.has(piece)).length;
1771
+ const union = mine.size + theirs.size - shared;
1772
+ return union === 0 || shared / union >= SAME_SITUATION;
1773
+ });
1774
+ }
1775
+ /** The words as the character said them, whatever quotes the game master put around them. */
1776
+ function asSpoken(segments, spoken) {
1777
+ const left = [...spoken];
1778
+ return segments.map((segment) => {
1779
+ if (segment.type !== "utterance") return segment;
1780
+ const at = left.findIndex((said) => said.character === segment.character && sameWords(said.text, segment.text));
1781
+ return at === -1 ? segment : {
1782
+ ...segment,
1783
+ text: left.splice(at, 1)[0].text
1784
+ };
3362
1785
  });
3363
1786
  }
3364
- /** The final decision for each character of the round: the retry's replaces the first attempt's. */
3365
- /** The player's character is never asked to act, so what the game master decided it did stands in for its report. */
3366
- function playerReport(state, outcome) {
3367
- const member = state.cast.find((candidate) => candidate.key === outcome.character && candidate.character.control === "player");
3368
- return member === void 0 ? void 0 : {
3369
- character: member.key,
3370
- name: member.character.name,
3371
- intent: outcome.summary,
3372
- commitment: "high"
1787
+ /**
1788
+ * The output the game master delivered, once it is acceptable: every utterance exactly once and in order, and the narration in the chat's language.
1789
+ * A refusal is thrown for the game master to correct; past `MAX_REFUSALS`, or when `silent`, the output is repaired instead.
1790
+ */
1791
+ function checkedOutput(narrationChecker, language, state, segments, silent) {
1792
+ const problems = [...segments.flatMap((segment, index) => segment.type === "utterance" && segment.character === "" ? [`segment ${index + 1}: an utterance needs the character who says it`] : []), ...narrationChecker.check(segments, state.utterances)];
1793
+ const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") });
1794
+ if (problems.length === 0 && wording !== void 0 && !silent && state.refused < 2) {
1795
+ state.refused += 1;
1796
+ throw new Error(`the output is not acceptable: ${wording}. Deliver it again with the narration corrected; utterances may not be touched`);
1797
+ }
1798
+ if (problems.length === 0) return {
1799
+ segments: asSpoken(segments, state.utterances),
1800
+ repaired: false
1801
+ };
1802
+ state.refused += 1;
1803
+ if (!silent && state.refused <= 2) throw new Error(`the output is not acceptable: ${problems.join("; ")}. Deliver it again with these corrected; narration may be written freely, utterances may not be touched`);
1804
+ return {
1805
+ segments: narrationChecker.repair(segments.filter((segment) => segment.type !== "utterance" || segment.character !== ""), state.utterances),
1806
+ repaired: true
3373
1807
  };
3374
1808
  }
3375
- function decisions(state) {
3376
- const decided = /* @__PURE__ */ new Map();
3377
- for (const attempt of [state.first, state.second]) for (const outcome of attempt?.outcomes ?? []) {
3378
- const report = attempt?.reports.find((candidate) => candidate.character === outcome.character) ?? playerReport(state, outcome);
3379
- if (report !== void 0) decided.set(outcome.character, {
3380
- outcome,
3381
- report
1809
+ //#endregion
1810
+ //#region src/host/dice/view.ts
1811
+ const sign = (value) => value >= 0 ? `+${value}` : String(value);
1812
+ /** A roll as the player reads it: what it was for, what fell, what it came to and what the world's check made of it. */
1813
+ function rollView(roll) {
1814
+ const kept = roll.kept.length < roll.faces.length ? ` (${roll.kept.join(", ")})` : "";
1815
+ const against = roll.target === void 0 ? "" : ` / ${roll.target}`;
1816
+ const outcome = roll.readout === void 0 ? "" : ` - ${roll.readout.label}${roll.readout.critical ? "!" : ""}`;
1817
+ return {
1818
+ id: roll.id,
1819
+ by: roll.by,
1820
+ text: `${roll.reason}: ${roll.expression} [${roll.faces.join(", ")}]${kept}${roll.modifier === 0 ? "" : ` ${sign(roll.modifier)}`} = ${roll.total}${against}${outcome}`
1821
+ };
1822
+ }
1823
+ /**
1824
+ * What the characters away from the player decide about what fell due, one commitment after another: their activity, and a move to where the commitment was when they
1825
+ * mean to keep it. It is recorded as a round only they perceive, and the keeper writes it.
1826
+ */
1827
+ async function runOffScene(deps, owner, state, store, due, limit) {
1828
+ const { summary, perCharacter, joint } = store.settings().offstage;
1829
+ let budget = limit;
1830
+ const acted = /* @__PURE__ */ new Map();
1831
+ for (const item of due) {
1832
+ if (budget <= 0) break;
1833
+ const cast = store.cast();
1834
+ const keys = item.characters.filter((key) => cast.some((member) => member.key === key) && (acted.get(key) ?? 0) < perCharacter).slice(0, budget);
1835
+ if (keys.length === 0) continue;
1836
+ budget -= keys.length;
1837
+ for (const key of keys) acted.set(key, (acted.get(key) ?? 0) + 1);
1838
+ const reports = [];
1839
+ for (const group of joint ? keys.map((key) => [key]) : [keys]) {
1840
+ const attending = reports.filter((report) => report.commitment !== "low").map((report) => `${report.name} has decided: ${report.intent}${report.utterance === void 0 ? "" : `, saying "${report.utterance}"`}.`);
1841
+ const asked = {
1842
+ ...state,
1843
+ situation: attending.length === 0 ? item.text : `${item.text}\n${attending.join("\n")}`,
1844
+ history: [],
1845
+ recalled: /* @__PURE__ */ new Map()
1846
+ };
1847
+ delete asked.first;
1848
+ delete asked.second;
1849
+ reports.push(...(await deps.ask(group, cast, asked, summary)).reports);
1850
+ }
1851
+ if (reports.length === 0) continue;
1852
+ const where = item.place;
1853
+ const moves = new Map(reports.flatMap((report) => {
1854
+ if (report.commitment === "low" || where === void 0) return [];
1855
+ const check = store.checkMove(report.character, {
1856
+ location: where,
1857
+ ignoreExits: true
1858
+ });
1859
+ return check.ok ? [[report.character, check]] : [];
1860
+ }));
1861
+ store.commit(reports.flatMap((report) => {
1862
+ const member = cast.find((candidate) => candidate.key === report.character);
1863
+ const move = moves.get(report.character);
1864
+ return member === void 0 ? [] : [{
1865
+ character: member.character.id,
1866
+ patch: { activity: report.intent },
1867
+ ...move?.ok === true ? { move: move.move } : {}
1868
+ }];
1869
+ }));
1870
+ state.offstage += 1;
1871
+ const time = store.time(owner.turn);
1872
+ store.queueCommit({
1873
+ turn: owner.turn,
1874
+ round: 100 + state.offstage,
1875
+ situation: item.text,
1876
+ offstage: true,
1877
+ time: {
1878
+ from: time.now,
1879
+ to: time.now,
1880
+ zone: time.zone
1881
+ },
1882
+ entries: reports.map((report) => {
1883
+ const at = cast.find((candidate) => candidate.key === report.character)?.place?.location;
1884
+ const move = moves.get(report.character);
1885
+ return {
1886
+ character: report.character,
1887
+ name: report.name,
1888
+ intent: report.intent,
1889
+ commitment: report.commitment,
1890
+ result: "succeeded",
1891
+ summary: report.intent,
1892
+ spoken: false,
1893
+ ...at === void 0 ? {} : { at: {
1894
+ key: locationKey(at),
1895
+ name: at.name
1896
+ } },
1897
+ ...move?.ok === true && move.plan.from !== move.move.to ? { moved: { ...move.to } } : {}
1898
+ };
1899
+ })
3382
1900
  });
1901
+ store.markHandled([item.key]);
1902
+ deps.write();
1903
+ if (summary && deps.stillThis()) {
1904
+ const lines = reports.flatMap((report) => report.account === void 0 ? [] : [report.account]);
1905
+ store.addNote("away", owner.turn, lines);
1906
+ }
3383
1907
  }
3384
- return decided;
3385
1908
  }
3386
1909
  //#endregion
3387
1910
  //#region src/host/orchestration/turn-engine.ts
3388
1911
  const MAX_OBJECTIONS = 3;
3389
1912
  /** The most a single round may be said to take: a day. A longer time passing is skipped with `advanceTime`. */
3390
1913
  const MAX_ROUND_SECONDS = 86400;
3391
- /** The game master is asked to correct its output this many times before it is corrected for it. */
3392
- const MAX_REFUSALS = 2;
3393
1914
  /** 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. */
3394
1915
  const MAX_FAILED_RUNS = 3;
3395
1916
  /**
@@ -3460,56 +1981,17 @@ var TurnEngine = class {
3460
1981
  const state = this.stateFor(owner);
3461
1982
  if (state.ooc?.question !== true) throw new Error("this turn is not an out-of-character question: there is nothing to answer");
3462
1983
  if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
3463
- const text = (await run(await this.askedRequest(owner, state.ooc.request, signal), signal)).trim();
1984
+ const text = (await run(await questionRequest(this.boundaries(), this.storeOf(owner), owner, state.ooc.request, signal), signal)).trim();
3464
1985
  if (text === "") throw new Error("the answer is empty");
3465
1986
  if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
3466
1987
  state.ooc.ruling = {
3467
1988
  legal: true,
3468
- note: text.length > 1200 ? `${text.slice(0, 1199)}…` : text,
1989
+ note: text.length > 1200 ? `${text.slice(0, MAX_OOC_ANSWER - 1)}…` : text,
3469
1990
  question: true
3470
1991
  };
3471
1992
  state.phase = "between";
3472
1993
  return state.ooc.ruling;
3473
1994
  }
3474
- /** 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. */
3475
- async askedRequest(owner, question, signal) {
3476
- const store = this.storeOf(owner);
3477
- const cast = store.cast();
3478
- const member = cast.find((candidate) => candidate.character.control === "player");
3479
- if (member === void 0) throw new Error("there is no player's character to answer for");
3480
- const queryVector = await store.queryVector(question, signal);
3481
- const memories = await this.boundaries().recaller.recall({
3482
- member,
3483
- situation: question,
3484
- turn: owner.turn,
3485
- policy: store.settings().memory,
3486
- ...queryVector === void 0 ? {} : { queryVector }
3487
- }, store.story, signal);
3488
- const place = member.place === void 0 ? void 0 : store.place(member.place.location.id);
3489
- const company = place === void 0 ? cast : place.here;
3490
- const relationships = knownRelationships(member, company, question, cast, store);
3491
- const carrying = store.carried(member.character.id);
3492
- const affiliations = store.affiliations(member.character.id);
3493
- const tracked = store.trackedFor(member.character.id, company.map((entry) => entry.character.id));
3494
- return {
3495
- member,
3496
- cast,
3497
- situation: question,
3498
- attempt: 1,
3499
- language: store.settings().prompts.language,
3500
- turn: owner.turn,
3501
- lookup: false,
3502
- text: (id, variables) => store.text(id, variables),
3503
- time: store.time(owner.turn),
3504
- knowledge: store.knowledge(member.character.id, owner.turn, company.map((entry) => entry.character.id)),
3505
- ...tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
3506
- ...place === void 0 ? {} : { place },
3507
- ...relationships.length === 0 ? {} : { relationships },
3508
- ...carrying.length === 0 ? {} : { carrying },
3509
- ...affiliations.length === 0 ? {} : { affiliations },
3510
- ...memories.length === 0 ? {} : { memories }
3511
- };
3512
- }
3513
1995
  /**
3514
1996
  * 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
3515
1997
  * what the player is told. Either way the turn goes on to its output; only a legal ruling lets the command change anything.
@@ -3536,7 +2018,7 @@ var TurnEngine = class {
3536
2018
  * 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.
3537
2019
  * @throws {Error} when the turn is not an ordinary one, was already judged, the reason is empty, or `at` is not a place.
3538
2020
  */
3539
- judge(owner, allowed, reason, at) {
2021
+ judge(owner, allowed, reason, at, uncertain) {
3540
2022
  const state = this.stateFor(owner);
3541
2023
  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"));
3542
2024
  if (state.phase !== "idle") throw new Error("the action is judged first, before anything else");
@@ -3565,6 +2047,14 @@ var TurnEngine = class {
3565
2047
  allowed,
3566
2048
  reason: why
3567
2049
  };
2050
+ const { tools } = this.storeOf(owner).settings();
2051
+ if (allowed && uncertain === true && (toolEnabled(tools, "gameMaster", "roll_check") || toolEnabled(tools, "gameMaster", "roll_dice"))) {
2052
+ state.rollWanted = true;
2053
+ return {
2054
+ ...state.judgement,
2055
+ roll: true
2056
+ };
2057
+ }
3568
2058
  return state.judgement;
3569
2059
  }
3570
2060
  /** The turn is an ordinary one: the game master judges the player's action before anything else. */
@@ -3586,6 +2076,7 @@ var TurnEngine = class {
3586
2076
  if (judgeDue(state)) throw new Error(explainPhase(state, "activate_characters"));
3587
2077
  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`);
3588
2078
  if (previewDue(state)) throw new Error(explainPhase(state, "activate_characters"));
2079
+ if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
3589
2080
  const store = this.storeOf(owner);
3590
2081
  const limit = store.settings().maxRounds;
3591
2082
  if (state.rounds >= limit) throw new Error(`${state.rounds} round${state.rounds === 1 ? "" : "s"} of characters were already played for this message, which is the most this chat allows: deliver the output with narrate`);
@@ -3607,7 +2098,7 @@ var TurnEngine = class {
3607
2098
  state.cues.clear();
3608
2099
  delete state.first;
3609
2100
  delete state.second;
3610
- const attempt = await this.runAttempt(owner, 1, keys, cast, state, run, signal);
2101
+ const attempt = await this.ask(owner, 1, keys, cast, state, run, signal);
3611
2102
  if (attempt.reports.length === 0) return {
3612
2103
  attempt: 1,
3613
2104
  reports: [],
@@ -3633,13 +2124,14 @@ var TurnEngine = class {
3633
2124
  if (state.ooc !== void 0) return { done: this.decree(owner, state, outcomes, elapsedSeconds) };
3634
2125
  if (state.phase === "idle" || state.phase === "between") {
3635
2126
  if (judgeDue(state) || previewDue(state)) throw new Error(explainPhase(state, "resolve_round"));
2127
+ if (rollDue(state, this.storeOf(owner))) throw new Error(ROLL_FIRST);
3636
2128
  const player = store.cast().find((member) => member.character.control === "player");
3637
2129
  if (player !== void 0 && outcomes.length === 1 && outcomes[0]?.character === player.key) return { done: this.resolvePlayer(owner, state, outcomes[0], elapsedSeconds) };
3638
2130
  }
3639
2131
  if (state.phase !== "resolving" && state.phase !== "retrying") throw new Error(explainPhase(state, "resolve_round"));
3640
2132
  const attempt = state.phase === "resolving" ? state.first : state.second;
3641
2133
  if (attempt === void 0) throw new Error("internal: no round to resolve");
3642
- checkOutcomes(attempt, outcomes, store, state.phase === "resolving" ? this.playerKey(state) : void 0);
2134
+ checkOutcomes(attempt, outcomes, store, state.phase === "resolving" ? this.playerKey(state) : void 0, void 0, state);
3643
2135
  if (elapsedSeconds !== void 0) state.elapsed = this.elapsedChecked(owner, elapsedSeconds);
3644
2136
  attempt.outcomes = [...outcomes];
3645
2137
  if (state.phase === "resolving") {
@@ -3648,7 +2140,7 @@ var TurnEngine = class {
3648
2140
  outcomes: attempt.outcomes
3649
2141
  }).filter((key) => attempt.reports.some((report) => report.character === key));
3650
2142
  if (retrying.length > 0) {
3651
- const second = await this.runAttempt(owner, 2, retrying, state.cast, state, run, signal);
2143
+ const second = await this.ask(owner, 2, retrying, state.cast, state, run, signal);
3652
2144
  state.second = second;
3653
2145
  if (second.reports.length > 0) {
3654
2146
  state.phase = "retrying";
@@ -3660,7 +2152,7 @@ var TurnEngine = class {
3660
2152
  }
3661
2153
  }
3662
2154
  }
3663
- return { done: this.finishRound(owner, state) };
2155
+ return { done: recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round)) };
3664
2156
  }
3665
2157
  /**
3666
2158
  * What an out-of-character command decrees, as one round of its own: outcomes for any characters, asked or not, each checked like any other
@@ -3679,7 +2171,7 @@ var TurnEngine = class {
3679
2171
  checkOutcomes({
3680
2172
  reports: [],
3681
2173
  failures: []
3682
- }, outcomes, store, void 0, state.cast);
2174
+ }, outcomes, store, void 0, state.cast, state);
3683
2175
  if (elapsedSeconds !== void 0) state.elapsed = this.elapsedChecked(owner, elapsedSeconds);
3684
2176
  state.situation = `By the player's out-of-character command (${state.ooc?.request ?? ""}), the game master decreed:`;
3685
2177
  state.recalled.clear();
@@ -3698,7 +2190,7 @@ var TurnEngine = class {
3698
2190
  failures: [],
3699
2191
  outcomes: [...outcomes]
3700
2192
  };
3701
- return this.finishRound(owner, state);
2193
+ return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
3702
2194
  }
3703
2195
  /** The key of the player's character. */
3704
2196
  playerKey(state) {
@@ -3718,7 +2210,7 @@ var TurnEngine = class {
3718
2210
  checkOutcomes({
3719
2211
  reports: [],
3720
2212
  failures: []
3721
- }, [outcome], store, outcome.character);
2213
+ }, [outcome], store, outcome.character, void 0, state);
3722
2214
  if (elapsedSeconds !== void 0) state.elapsed = this.elapsedChecked(owner, elapsedSeconds);
3723
2215
  state.situation = `${player?.character.name ?? outcome.character}: ${outcome.summary}`;
3724
2216
  state.recalled.clear();
@@ -3728,7 +2220,7 @@ var TurnEngine = class {
3728
2220
  failures: [],
3729
2221
  outcomes: [outcome]
3730
2222
  };
3731
- return this.finishRound(owner, state);
2223
+ return recordRound(this.storeOf(owner), owner, state, (round) => this.fire(owner, round));
3732
2224
  }
3733
2225
  /**
3734
2226
  * The game master shows the player how the scene opens, before anyone is asked: something to read while the rest of the turn is worked out.
@@ -3831,78 +2323,15 @@ var TurnEngine = class {
3831
2323
  return await this.deliver(owner, state, typed, false, run);
3832
2324
  }
3833
2325
  /**
3834
- * The game master asks for something to be made up (a place the story has gone to, someone who has
3835
- * joined): the world author decides whether the story genuinely needs it, and makes it or says why not.
3836
- * The world may be closed, and only so many things may be made up in a turn.
3837
- * @throws {Error} when the world is closed, the limit of the turn is reached, a round is open, or the request is empty.
2326
+ * The game master asks for something to be made up (a place the story has gone to, someone who has joined): the world author decides whether the
2327
+ * story genuinely needs it, and makes it or says why not. @throws {Error} when the world is closed, the turn's limit is reached or a round is open.
3838
2328
  */
3839
2329
  async expand(owner, input, signal) {
3840
- const state = this.stateFor(owner);
3841
- if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: the world is extended between rounds, not in the middle of one");
3842
- const blocked = oocBlock(state);
3843
- if (blocked !== void 0) throw new Error(blocked);
3844
- const need = AUTHORING_NEEDS.find((candidate) => candidate === input.need);
3845
- if (need === void 0) throw new Error(`"${input.need}" is not a reason to make something up; the reasons are: ${AUTHORING_NEEDS.join(", ")}`);
3846
- const what = input.what.trim();
3847
- if (what === "") throw new Error("say what is needed, from what the story has established: who or where, and why now");
3848
- const store = this.storeOf(owner);
3849
- const { authoring } = store.settings();
3850
- if (!authoring.enabled) throw new Error("this world is closed: nothing can be made up in it");
3851
- const made = store.story.consolidation.createdIn(owner.turn).length;
3852
- if (made >= authoring.perTurn) throw new Error(`${made} new thing${made === 1 ? " was" : "s were"} already made up this turn, which is the most this chat allows: work with what exists`);
3853
- return await this.boundaries().author.create({
3854
- chat: owner.chat,
3855
- turn: owner.turn,
3856
- need,
3857
- what,
3858
- store
3859
- }, signal);
2330
+ return await expandWorld(this.boundaries(), this.storeOf(owner), this.stateFor(owner), owner, input, signal);
3860
2331
  }
3861
- /**
3862
- * The game master introduces a thing the story uses, as a table's game master would: it is made at once where the game master says
3863
- * (a place, someone's hands, a container; the player's place when it says nothing), with no world author asked.
3864
- * @throws {Error} when the world is closed, a round is open, the turn's allowance is used, or the thing cannot be put where it was said.
3865
- */
2332
+ /** The game master introduces a thing the story uses, with no world author asked. @throws {Error} when the world is closed, a round is open, or the thing cannot be put where it was said. */
3866
2333
  introduce(owner, input) {
3867
- const state = this.stateFor(owner);
3868
- if (state.phase === "resolving" || state.phase === "retrying") throw new Error("resolve the round first: things are introduced between rounds, not in the middle of one");
3869
- const blocked = oocBlock(state);
3870
- if (blocked !== void 0) throw new Error(blocked);
3871
- const name = input.name.trim();
3872
- if (name === "") throw new Error("name the thing");
3873
- const store = this.storeOf(owner);
3874
- const { authoring } = store.settings();
3875
- if (!authoring.enabled) throw new Error("this world is closed: nothing can be made up in it");
3876
- const kept = store.story.consolidation.createdIn(owner.turn).filter((entry) => entry.kind === "item").length;
3877
- if (kept >= authoring.thingsPerTurn) throw new Error(`${kept} thing${kept === 1 ? " was" : "s were"} already introduced this turn, which is the most this chat allows`);
3878
- if ([
3879
- input.at,
3880
- input.heldBy,
3881
- input.inside
3882
- ].filter((entry) => entry !== void 0 && entry.trim() !== "").length > 1) throw new Error("say where it is in one way only: at a place, held by a character, or inside a thing");
3883
- const here = store.cast().find((member) => member.character.control === "player")?.place?.location;
3884
- const placed = input.heldBy !== void 0 && input.heldBy.trim() !== "" ? { heldBy: input.heldBy.trim() } : input.inside !== void 0 && input.inside.trim() !== "" ? { inside: input.inside.trim() } : input.at !== void 0 && input.at.trim() !== "" ? { at: { location: input.at.trim() } } : here === void 0 ? void 0 : { at: { location: locationKey(here) } };
3885
- if (placed === void 0) throw new Error("say where it is: no place is known for the player, so name a place (at), a holder (held_by) or a container (inside)");
3886
- const key = uniqueKey(slug(name, "thing"), new Set(store.story.items.list().map((item) => item.sourceId).filter((entry) => entry !== void 0)));
3887
- store.story.edit({
3888
- turn: owner.turn,
3889
- items: [{
3890
- key,
3891
- name,
3892
- ...input.description === void 0 || input.description.trim() === "" ? {} : { description: input.description.trim() },
3893
- ...input.quantity === void 0 ? {} : { quantity: input.quantity },
3894
- ...input.quality === void 0 || input.quality.trim() === "" ? {} : { quality: input.quality.trim() },
3895
- ...input.notable === void 0 ? {} : { notable: input.notable },
3896
- ...input.hidden === void 0 ? {} : { hidden: input.hidden },
3897
- ...placed,
3898
- note: "introduced by the game master"
3899
- }]
3900
- });
3901
- return {
3902
- key,
3903
- name,
3904
- where: "heldBy" in placed ? `held by ${placed.heldBy}` : "inside" in placed ? `inside ${placed.inside}` : `at ${placed.at.location}`
3905
- };
2334
+ return introduceThing(this.storeOf(owner), this.stateFor(owner), owner, input);
3906
2335
  }
3907
2336
  /** Whether made-up characters and places are waiting to be fitted into the world. */
3908
2337
  waitingToFit(owner) {
@@ -3930,7 +2359,7 @@ var TurnEngine = class {
3930
2359
  }
3931
2360
  runOffScene(owner, state, store, due, limit, run) {
3932
2361
  return runOffScene({
3933
- ask: (group, cast, asked, summary) => this.runAttempt(owner, 1, group, cast, asked, run, state.cancel.signal, summary),
2362
+ ask: (group, cast, asked, summary) => this.ask(owner, 1, group, cast, asked, run, state.cancel.signal, summary),
3934
2363
  write: () => {
3935
2364
  this.write(owner, state);
3936
2365
  },
@@ -4060,6 +2489,8 @@ var TurnEngine = class {
4060
2489
  reports: [],
4061
2490
  outcomes: [],
4062
2491
  utterances: [],
2492
+ cited: /* @__PURE__ */ new Set(),
2493
+ reported: /* @__PURE__ */ new Set(),
4063
2494
  refused: 0,
4064
2495
  previewed: false,
4065
2496
  previewWanted: this.stores(chat)?.settings().preview.enabled ?? false,
@@ -4079,236 +2510,15 @@ var TurnEngine = class {
4079
2510
  if (store === void 0) throw new Error("this chat is not a roleplay session");
4080
2511
  return store;
4081
2512
  }
4082
- /** Every character acts at the same time; one that fails or answers badly is reported, not fatal. */
4083
- async runAttempt(owner, number, keys, cast, state, run, signal, away = false) {
4084
- const store = this.stores(owner.chat);
4085
- const { outputValidator } = this.boundaries();
4086
- const reaction = number === 2 ? reactions(state) : void 0;
4087
- const queryVector = number === 1 && store !== void 0 ? await store.queryVector(state.situation, signal) : void 0;
4088
- const time = store?.time(owner.turn);
4089
- const answers = await Promise.all(keys.map(async (key) => {
4090
- const member = cast.find((candidate) => candidate.key === key);
4091
- if (member === void 0) return {
4092
- character: key,
4093
- name: key,
4094
- reason: "no such character"
4095
- };
4096
- const previous = number === 2 ? state.first?.reports.find((report) => report.character === key) : void 0;
4097
- const memories = number === 1 && store !== void 0 ? await this.boundaries().recaller.recall({
4098
- member,
4099
- situation: state.situation,
4100
- turn: owner.turn,
4101
- policy: store.settings().memory,
4102
- ...store.settings().diagnostics.keepRuns ? { explain: true } : {},
4103
- ...queryVector === void 0 ? {} : { queryVector }
4104
- }, store.story, signal) : state.recalled.get(key) ?? [];
4105
- if (number === 1 && memories.length > 0) state.recalled.set(key, memories);
4106
- const place = member.place === void 0 ? void 0 : store?.place(member.place.location.id);
4107
- const relationships = store === void 0 ? [] : knownRelationships(member, place === void 0 ? cast : place.here, state.situation, cast, store);
4108
- const carrying = store === void 0 ? [] : store.carried(member.character.id);
4109
- const knowledge = store?.knowledge(member.character.id, owner.turn, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
4110
- const affiliations = store?.affiliations(member.character.id) ?? [];
4111
- const agenda = store?.agenda(owner.turn, member.character.id);
4112
- const cues = cuesOf(state, key, member, store, number);
4113
- const upcoming = store?.upcomingFor(member.character.id, owner.turn) ?? [];
4114
- const tracked = store?.trackedFor(member.character.id, (place === void 0 ? cast : place.here).map((entry) => entry.character.id));
4115
- const request = {
4116
- member,
4117
- cast,
4118
- situation: state.situation,
4119
- attempt: number,
4120
- language: store?.settings().prompts.language ?? "en",
4121
- turn: owner.turn,
4122
- ...away ? { away: true } : {},
4123
- lookup: store?.settings().memory.lookup ?? false,
4124
- text: (id, variables) => this.storeOf(owner).text(id, variables),
4125
- ...time === void 0 ? {} : { time },
4126
- ...agenda === void 0 ? {} : { agenda },
4127
- ...cues.length === 0 ? {} : { cues },
4128
- ...upcoming.length === 0 ? {} : { upcoming },
4129
- ...tracked === void 0 || tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
4130
- ...place === void 0 ? {} : { place },
4131
- ...relationships.length === 0 ? {} : { relationships },
4132
- ...carrying.length === 0 ? {} : { carrying },
4133
- ...knowledge === void 0 ? {} : { knowledge },
4134
- ...affiliations.length === 0 ? {} : { affiliations },
4135
- ...memories.length === 0 ? {} : { memories },
4136
- ...state.history.length === 0 ? {} : { earlier: [...state.history] },
4137
- ...reaction === void 0 ? {} : { reaction },
4138
- ...previous === void 0 ? {} : { previous: {
4139
- intent: previous.intent,
4140
- commitment: previous.commitment
4141
- } }
4142
- };
4143
- try {
4144
- const action = await run(request, signal);
4145
- const verdict = outputValidator.validate(action, request);
4146
- if (!verdict.ok) return {
4147
- character: key,
4148
- name: member.character.name,
4149
- reason: verdict.reason
4150
- };
4151
- return {
4152
- character: key,
4153
- name: member.character.name,
4154
- ...action
4155
- };
4156
- } catch (error) {
4157
- if (signal.aborted) throw error;
4158
- const reason = error instanceof Error ? error.message : String(error);
4159
- this.problem(`${member.character.name} could not act: ${reason}`);
4160
- return {
4161
- character: key,
4162
- name: member.character.name,
4163
- reason,
4164
- technical: true
4165
- };
2513
+ ask(owner, number, keys, cast, state, run, signal, away = false) {
2514
+ return askCharacters({
2515
+ boundaries: this.boundaries(),
2516
+ store: this.stores(owner.chat),
2517
+ storeOf: (o) => this.storeOf(o),
2518
+ problem: (message) => {
2519
+ this.problem(message);
4166
2520
  }
4167
- }));
4168
- return {
4169
- reports: answers.filter((answer) => "intent" in answer),
4170
- failures: answers.filter((answer) => "reason" in answer)
4171
- };
4172
- }
4173
- finishRound(owner, state) {
4174
- const store = this.storeOf(owner);
4175
- const decided = decisions(state);
4176
- const limit = store.settings().maxRounds;
4177
- const round = state.rounds + 1;
4178
- const checked = new Map([...decided.values()].flatMap(({ outcome }) => outcome.moveTo === void 0 ? [] : [[outcome.character, store.checkMove(outcome.character, outcome.moveTo)]]));
4179
- const refused = [...checked].flatMap(([character, check]) => check.ok ? [] : [`${character}: ${check.problems.join("; ")}`]);
4180
- if (refused.length > 0) throw new Error(`a move is no longer possible: ${refused.join("; ")}`);
4181
- const spoken = [...decided.values()].flatMap(({ outcome, report }) => report.utterance === void 0 || outcome.spoken === false || state.utterances.some((said) => said.character === report.character && sameWords(said.text, report.utterance)) ? [] : [{
4182
- character: report.character,
4183
- name: report.name,
4184
- text: report.utterance,
4185
- round
4186
- }]);
4187
- state.rounds = round;
4188
- state.situations.push(state.situation);
4189
- state.utterances.push(...spoken);
4190
- for (const { outcome, report } of decided.values()) {
4191
- state.reports.push(report);
4192
- state.outcomes.push(outcome);
4193
- state.history.push({
4194
- round,
4195
- character: report.character,
4196
- name: report.name,
4197
- intent: report.intent,
4198
- ...report.utterance === void 0 ? {} : { utterance: report.utterance },
4199
- result: outcome.result,
4200
- summary: outcome.summary
4201
- });
4202
- }
4203
- state.limit = limit;
4204
- state.phase = "between";
4205
- const playerPlace = state.cast.find((member) => member.character.control === "player")?.place?.location;
4206
- const updates = [...decided.values()].flatMap(({ outcome, report }) => {
4207
- const member = state.cast.find((candidate) => candidate.key === report.character);
4208
- if (member === void 0) return [];
4209
- const check = checked.get(outcome.character);
4210
- return [{
4211
- key: report.character,
4212
- update: {
4213
- character: member.character.id,
4214
- patch: {
4215
- activity: outcome.summary,
4216
- ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() }
4217
- },
4218
- ...check?.ok === true ? { move: check.move } : {},
4219
- ...outcome.itemChanges === void 0 || outcome.itemChanges.length === 0 ? {} : { items: outcome.itemChanges }
4220
- }
4221
- }];
4222
- });
4223
- const effects = /* @__PURE__ */ new Map();
4224
- const done = store.commit(updates.map((entry) => entry.update));
4225
- updates.forEach(({ key }, index) => {
4226
- effects.set(key, done[index] ?? []);
4227
- });
4228
- const tracked = new Map(updates.map(({ key }) => [key, store.changeVariables(owner.turn, decided.get(key)?.outcome.variableChanges ?? []).map((effect) => ({
4229
- subject: effect.subjectName,
4230
- name: effect.variable.name,
4231
- from: describeValue(effect.variable, effect.from),
4232
- to: describeValue(effect.variable, effect.to)
4233
- }))]));
4234
- const journey = [...checked].flatMap(([character, check]) => check.ok && state.cast.find((candidate) => candidate.key === character)?.character.control === "player" ? [check.plan.travelSeconds ?? 0] : [])[0];
4235
- const time = store.endRound(owner.turn, round, state.elapsed, journey);
4236
- delete state.elapsed;
4237
- const world = this.fire(owner, round);
4238
- store.queueCommit({
4239
- turn: owner.turn,
4240
- round,
4241
- situation: state.situation,
4242
- ...playerPlace === void 0 ? {} : { place: {
4243
- key: locationKey(playerPlace),
4244
- name: playerPlace.name
4245
- } },
4246
- time: {
4247
- from: time.from,
4248
- to: time.to,
4249
- zone: time.zone
4250
- },
4251
- entries: [...decided.values()].map(({ outcome, report }) => {
4252
- const at = state.cast.find((candidate) => candidate.key === report.character)?.place?.location;
4253
- const check = checked.get(outcome.character);
4254
- return {
4255
- character: report.character,
4256
- name: report.name,
4257
- intent: report.intent,
4258
- commitment: report.commitment,
4259
- ...report.utterance === void 0 ? {} : { utterance: report.utterance },
4260
- result: outcome.result,
4261
- summary: outcome.summary,
4262
- ...outcome.publicState === void 0 || outcome.publicState.trim() === "" ? {} : { publicState: outcome.publicState.trim() },
4263
- spoken: outcome.spoken !== false,
4264
- ...(tracked.get(report.character) ?? []).length === 0 ? {} : { variables: tracked.get(report.character) },
4265
- ...state.cast.find((candidate) => candidate.key === report.character)?.character.control === "player" ? { player: true } : {},
4266
- ...report.forced === true ? { forced: true } : {},
4267
- ...(effects.get(report.character) ?? []).length === 0 ? {} : { items: (effects.get(report.character) ?? []).map((effect) => ({
4268
- name: effect.item.name,
4269
- action: effect.action,
4270
- summary: effect.summary
4271
- })) },
4272
- ...at === void 0 ? {} : { at: {
4273
- key: locationKey(at),
4274
- name: at.name
4275
- } },
4276
- ...check?.ok === true && check.plan.from !== check.move.to ? { moved: {
4277
- ...check.to,
4278
- ...check.position === void 0 ? {} : { position: check.position }
4279
- } } : {}
4280
- };
4281
- })
4282
- });
4283
- return {
4284
- round,
4285
- limit,
4286
- updated: [...decided.keys()],
4287
- retryFailures: state.second?.failures ?? [],
4288
- utterances: spoken,
4289
- spoken: [...state.utterances],
4290
- waiting: store.pendingCommits().length,
4291
- variables: [...tracked.values()].flat().map((change) => `${change.subject}'s ${change.name} is now ${change.to} (it was ${change.from})`),
4292
- time: {
4293
- from: time.from,
4294
- to: time.to,
4295
- zone: time.zone
4296
- },
4297
- moved: time.moved,
4298
- world,
4299
- things: [...effects].flatMap(([character, list]) => list.map((effect) => ({
4300
- character,
4301
- name: effect.item.name,
4302
- action: effect.action,
4303
- summary: effect.summary
4304
- }))),
4305
- moves: [...checked].flatMap(([character, check]) => check.ok && check.plan.from !== check.move.to ? [{
4306
- character,
4307
- name: decided.get(character)?.report.name ?? character,
4308
- to: check.to.name,
4309
- via: Math.max(0, check.plan.via.length - 1)
4310
- }] : [])
4311
- };
2521
+ }, owner, number, keys, cast, state, run, signal, away);
4312
2522
  }
4313
2523
  /**
4314
2524
  * The game master asks for what happened to be written into the story's lasting records. The memory
@@ -4398,30 +2608,17 @@ var TurnEngine = class {
4398
2608
  if ((this.runs.get(owner.chat) ?? 0) === 0 && store !== void 0 && waiting > 0 && (state.requested || waiting >= store.settings().memory.backlogRounds)) this.write(owner, state);
4399
2609
  }
4400
2610
  async deliver(owner, state, segments, silent, run) {
4401
- const { narrationChecker } = this.boundaries();
4402
- const problems = [...segments.flatMap((segment, index) => segment.type === "utterance" && segment.character === "" ? [`segment ${index + 1}: an utterance needs the character who says it`] : []), ...narrationChecker.check(segments, state.utterances)];
4403
- const wording = wrongLanguage(this.storeOf(owner).settings().prompts.language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") });
4404
- if (problems.length === 0 && wording !== void 0 && !silent && state.refused < MAX_REFUSALS) {
4405
- state.refused += 1;
4406
- throw new Error(`the output is not acceptable: ${wording}. Deliver it again with the narration corrected; utterances may not be touched`);
4407
- }
4408
- let output;
4409
- if (problems.length === 0) output = {
4410
- segments: asSpoken(segments, state.utterances),
4411
- repaired: false
4412
- };
4413
- else {
4414
- state.refused += 1;
4415
- if (!silent && state.refused <= MAX_REFUSALS) throw new Error(`the output is not acceptable: ${problems.join("; ")}. Deliver it again with these corrected; narration may be written freely, utterances may not be touched`);
4416
- output = {
4417
- segments: narrationChecker.repair(segments.filter((segment) => segment.type !== "utterance" || segment.character !== ""), state.utterances),
4418
- repaired: true
4419
- };
4420
- }
2611
+ let output = checkedOutput(this.boundaries().narrationChecker, this.storeOf(owner).settings().prompts.language, state, segments, silent);
4421
2612
  if (state.ooc?.ruling !== void 0) output = {
4422
2613
  ...output,
4423
2614
  ooc: state.ooc.ruling
4424
2615
  };
2616
+ const store = this.storeOf(owner);
2617
+ const rolled = store.settings().dice.visibility === "card" ? store.story.dice.rolls({ turn: owner.turn }) : [];
2618
+ if (rolled.length > 0) output = {
2619
+ ...output,
2620
+ rolls: rolled.map(rollView)
2621
+ };
4425
2622
  this.storeOf(owner).completeTurn();
4426
2623
  this.storeOf(owner).resolveBeats(state.addressed);
4427
2624
  state.phase = "done";
@@ -4724,6 +2921,23 @@ function apply(ctx) {
4724
2921
  settings: liveSettings(sessionFolder(sessionsDir(), session), problem)
4725
2922
  };
4726
2923
  };
2924
+ /** What the game master is told of the dice, when it has a dice tool; nothing when it has none. */
2925
+ const diceSection = (context, chat, language) => {
2926
+ const chatId = context.agent?.session.id;
2927
+ const store = chatId === void 0 ? void 0 : stores(chatId);
2928
+ if (chat === void 0 || store === void 0) return "";
2929
+ const on = [
2930
+ "roll_check",
2931
+ "roll_dice",
2932
+ "list_checks"
2933
+ ].filter((tool) => toolEnabled(chat.settings.tools, "gameMaster", tool));
2934
+ if (on.length === 0) return "";
2935
+ const checks = on.includes("roll_check") ? describeChecks(store.story.dice.checks(), translator(languageOf(language))) : "";
2936
+ return ctx.roleplayPrompts.text("roleplay/dice", language, {
2937
+ tools: on.join(", "),
2938
+ checks
2939
+ }, chat.session);
2940
+ };
4727
2941
  for (const [name, order, id] of [[
4728
2942
  PERSONA_SECTION,
4729
2943
  ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),
@@ -4740,10 +2954,22 @@ function apply(ctx) {
4740
2954
  const chat = settingsOf(context);
4741
2955
  const language = chat?.settings.prompts.language ?? "en";
4742
2956
  const part = (name) => ctx.roleplayPrompts.text(name, language, {}, chat?.session);
4743
- const variables = id === "roleplay/game-master" ? { preview: chat?.settings.preview.enabled === false ? "" : part("roleplay/preview") } : id === "roleplay/persona" ? { style: part("roleplay/style") } : {};
2957
+ const variables = id === "roleplay/game-master" ? {
2958
+ preview: chat?.settings.preview.enabled === false ? "" : part("roleplay/preview"),
2959
+ dice: diceSection(context, chat, language)
2960
+ } : id === "roleplay/persona" ? { style: part("roleplay/style") } : {};
4744
2961
  return ctx.roleplayPrompts.text(id, language, variables, chat?.session);
4745
2962
  }
4746
2963
  });
2964
+ ctx.systemPrompt.section({
2965
+ name: RESOURCE_HINT_SECTION,
2966
+ order: ctx.systemPrompt.getSectionOrder("MCP_SERVERS"),
2967
+ interpolate: false,
2968
+ text: (context) => {
2969
+ const chat = settingsOf(context);
2970
+ return resourceHint(ctx.tools.schemas(context.scope).map((tool) => tool.name), ctx.tools.schemas().map((tool) => tool.name), translator(languageOf(chat?.settings.prompts.language ?? "en")));
2971
+ }
2972
+ });
4747
2973
  const [previewTool, ...tools] = [...createTools$1({
4748
2974
  engine,
4749
2975
  boundaries,
@@ -4814,12 +3040,21 @@ function apply(ctx) {
4814
3040
  ctx.roleplayOrchestration.images = void 0;
4815
3041
  };
4816
3042
  }, "roleplay: images");
3043
+ const diceLink = (chat) => {
3044
+ const store = stores(chat);
3045
+ const agent = ctx.agents.get(SessionId(chat));
3046
+ return store === void 0 || agent === void 0 ? void 0 : {
3047
+ session: store.story,
3048
+ turn: currentTurn(agent)
3049
+ };
3050
+ };
4817
3051
  installHooks(ctx, {
4818
3052
  engine,
4819
3053
  boundaries,
4820
3054
  stores,
4821
3055
  timelines,
4822
- previewTool
3056
+ previewTool,
3057
+ optionalTools: createDiceTools(diceLink)
4823
3058
  });
4824
3059
  }
4825
3060
  //#endregion