@dsh-agentic-roleplay/core 0.3.2 → 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.
@@ -1,17 +1,20 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { B as shippedText, S as wrongLanguage, W as ReflectionRefusedError, Y as INTENT_STATUSES, _ as API_PREFIX } from "./packs-BCGK9KZV.js";
3
- import { B as sameWords, D as parseOoc, E as MAX_OOC_ANSWER, G as readTime, H as beginTurn, I as Timelines, J as referent, K as skipTime, M as readNotes, N as observeAsPlayer, O as addToNote, P as observeSurroundings, S as plotAuthorNeeded, T as AUTHORING_NEEDS, U as describeWhen, V as ClockError, W as endRound, X as languageOf, Y as RESULTS, Z as translator, _ as PREVIEW_TOOL, b as describePacingAdvice, c as dueReflection, f as whereabouts, g as toolEnabled, h as externalWithheld, i as keepRunDetail, j as putNote, k as clearNotes, l as memoryReflector, p as externalGiven, q as zoneOf, r as forgetRunDetails, s as recordActivity, t as deliverNow, u as recordFailure, v as createTools$1, x as pacingAdvice } from "./deliver-BSsDtF6X.js";
4
- import { a as WORLD_RULES_KEY, o as rulesOf } from "./settings-CA6icLL_.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";
5
7
  import { a as liveSettings } from "./narration-DK2kiIjE.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-BzeepLd2.js";
7
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DS5-qH9F.js";
8
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Cp-J0onD.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
16
  import { readdir } from "node:fs/promises";
14
- import { ENGAGEMENT_GRACE, InvalidEditError, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, characterKey, createDiceTools, createTools, dayPart, describeDuration, describeHolder, describeInstant, describeValue, inAudience, itemKey, judgedStatements, lintWorld, localTime, locationKey, mentioned, nextOccurrence, occurrenceAt, parseInstant, parseRecordsEdit, planItemChange, planVariableChange, rollPlain, 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";
15
18
  //#region src/host/tools/resource-hint.ts
16
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. */
17
20
  const RESOURCE_HINT_SECTION = "mcp-resource-servers";
@@ -131,20 +134,23 @@ const RESULT$3 = {
131
134
  function keeperTools(job, memory, progress) {
132
135
  const turn = Math.max(...job.rounds.map((round) => round.turn));
133
136
  const keys = job.store.story.characters.list().map(characterKey);
137
+ const { tools } = job.store.settings();
134
138
  const wanted = /* @__PURE__ */ new Set([
135
139
  "read_records",
136
140
  "edit_records",
137
- "search_events",
138
- "list_threads",
139
141
  "list_locations",
140
142
  "get_location",
141
143
  "list_factions",
142
144
  "get_faction",
143
- "list_relationships",
144
- "list_items",
145
145
  "get_item",
146
146
  "get_agenda",
147
- "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))
148
154
  ]);
149
155
  return createTools(() => ({
150
156
  session: job.store.story,
@@ -309,31 +315,6 @@ function suggestionWriter(deps) {
309
315
  } };
310
316
  }
311
317
  //#endregion
312
- //#region src/host/triggers/judged.ts
313
- const KEY = "triggers.judged";
314
- function readVerdicts(session) {
315
- const stored = session.metadata.getValue(KEY);
316
- if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
317
- const verdicts = {};
318
- for (const [statement, value] of Object.entries(stored)) {
319
- const verdict = value;
320
- if (typeof verdict === "object" && verdict !== null && typeof verdict.holds === "boolean" && typeof verdict.turn === "number") verdicts[statement] = {
321
- holds: verdict.holds,
322
- turn: verdict.turn
323
- };
324
- }
325
- return verdicts;
326
- }
327
- /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
328
- function writeVerdicts(session, verdicts, keep) {
329
- session.metadata.setValue(KEY, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
330
- }
331
- /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
332
- const verdictReader = (session) => {
333
- const verdicts = readVerdicts(session);
334
- return (statement) => verdicts[statement]?.holds === true;
335
- };
336
- //#endregion
337
318
  //#region src/host/triggers/judge.ts
338
319
  const RESULT$1 = {
339
320
  type: "object",
@@ -440,7 +421,7 @@ const DECISION_LIMITS = [
440
421
  ...Array.from({ length: 6 }, () => 200),
441
422
  ...Array.from({ length: MAX_ACTIVE_GOALS }, () => 10)
442
423
  ];
443
- const keyOf$1 = (faction) => faction.sourceId ?? String(faction.id);
424
+ const keyOf = (faction) => faction.sourceId ?? String(faction.id);
444
425
  function lastActed(session) {
445
426
  const stored = session.metadata.getValue(LAST_KEY);
446
427
  return typeof stored === "object" && stored !== null && !Array.isArray(stored) ? Object.fromEntries(Object.entries(stored).filter((entry) => typeof entry[1] === "number")) : {};
@@ -453,7 +434,7 @@ function dueFactions(session, now, everyDays) {
453
434
  const last = lastActed(session);
454
435
  const due = [];
455
436
  for (const faction of session.factions.list()) {
456
- const key = keyOf$1(faction);
437
+ const key = keyOf(faction);
457
438
  if (last[key] === void 0) {
458
439
  last[key] = now;
459
440
  continue;
@@ -471,7 +452,7 @@ function dueFactions(session, now, everyDays) {
471
452
  function markActed(session, faction, now) {
472
453
  session.metadata.setValue(LAST_KEY, {
473
454
  ...lastActed(session),
474
- [keyOf$1(faction)]: now
455
+ [keyOf(faction)]: now
475
456
  });
476
457
  }
477
458
  const RESULT = {
@@ -616,7 +597,7 @@ function factionStrategist(deps) {
616
597
  ...childModel(store.settings(), "authoring"),
617
598
  trace: childTrace(store, "authoring", `faction ${faction.name}`),
618
599
  persona: promptFor(parent, "roleplay/faction-strategist", store.settings().prompts.language),
619
- prompt: brief(session, faction, now, zone, last[keyOf$1(faction)] ?? now),
600
+ prompt: brief(session, faction, now, zone, last[keyOf(faction)] ?? now),
620
601
  result: RESULT,
621
602
  maxCalls: 3
622
603
  });
@@ -951,990 +932,6 @@ function worldAuthor(deps) {
951
932
  };
952
933
  }
953
934
  //#endregion
954
- //#region src/host/triggers/notes.ts
955
- /** 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. */
956
- function fireTriggers(session, input) {
957
- const { settings, turn, round, now, zone, problem } = input;
958
- if (!settings.triggers.enabled) return { fired: [] };
959
- const before = Math.max(0, ...session.triggers.notes().map((note) => note.id));
960
- const run = session.runTriggers({
961
- turn,
962
- round,
963
- now,
964
- zone,
965
- maxFires: settings.triggers.maxFires,
966
- judged: verdictReader(session)
967
- });
968
- for (const failure of run.failed) problem(`the trigger "${failure.trigger.key}" could not fire and is given up: ${failure.problem}`);
969
- const names = new Map(session.characters.list().map((character) => [character.id, character.name]));
970
- const fresh = session.triggers.notes({ status: "pending" }).filter((note) => note.id > before);
971
- const told = new Map(deliverNow(session, fresh, {
972
- now,
973
- zone
974
- }).map((entry) => [entry.id, entry.text]));
975
- return { fired: run.fired.map((fired) => ({
976
- name: fired.trigger.name,
977
- events: fired.events,
978
- cues: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "cue" && told.has(note.id)).map((note) => ({
979
- names: note.characterIds.flatMap((id) => names.get(id) ?? []),
980
- text: told.get(note.id)
981
- })),
982
- beats: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "beat" && told.has(note.id)).map((note) => ({
983
- id: note.id,
984
- text: told.get(note.id)
985
- }))
986
- })) };
987
- }
988
- /** When something is to happen, as it is told: the date and how far off it is. */
989
- function whenText(at, clock) {
990
- if (at === void 0) return void 0;
991
- return `${describeInstant(at, clock.zone)}${at > clock.now ? `, in ${describeDuration(at - clock.now)}` : ""}`;
992
- }
993
- function whoKnows(session, announcement) {
994
- const { audience } = announcement;
995
- if (audience === "everyone") return "everyone";
996
- if ("place" in audience) return `whoever is at ${session.locations.list().find((place) => locationKey(place) === audience.place)?.name ?? audience.place}`;
997
- return audience.characters.map((key) => session.characters.list().find((entry) => (entry.sourceId ?? String(entry.id)) === key)?.name ?? key).join(", ");
998
- }
999
- /** At most this many announcements are told to one character at once: soonest first. */
1000
- const MAX_UPCOMING_FOR_CHARACTER = 3;
1001
- /** 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. */
1002
- function noteStore(session, settings, clock) {
1003
- return {
1004
- upcoming: (turn) => {
1005
- const now = clock(turn);
1006
- return announcements(session, now).map((entry) => {
1007
- const when = whenText(entry.at, now);
1008
- return {
1009
- text: entry.text,
1010
- who: whoKnows(session, entry),
1011
- ...when === void 0 ? {} : { when }
1012
- };
1013
- });
1014
- },
1015
- upcomingFor: (characterId, turn) => {
1016
- const now = clock(turn);
1017
- return announcements(session, now).filter((entry) => inAudience(session, entry.audience, characterId)).slice(0, MAX_UPCOMING_FOR_CHARACTER).map((entry) => {
1018
- const when = whenText(entry.at, now);
1019
- return {
1020
- text: entry.text,
1021
- ...when === void 0 ? {} : { when }
1022
- };
1023
- });
1024
- },
1025
- pendingBeats: () => deliverNow(session, session.triggers.notes({
1026
- status: "pending",
1027
- kind: "beat"
1028
- }), clock(session.metadata.get().turns + 1)),
1029
- resolveBeats: (ids) => {
1030
- const pending = new Set(session.triggers.notes({
1031
- status: "pending",
1032
- kind: "beat"
1033
- }).map((note) => note.id));
1034
- const unknown = ids.filter((id) => !pending.has(id));
1035
- 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`);
1036
- session.transaction(() => {
1037
- for (const id of ids) session.triggers.resolveNote(id, "done");
1038
- });
1039
- },
1040
- cuesFor: (characterId) => deliverNow(session, session.triggers.notes({
1041
- status: "pending",
1042
- kind: "cue"
1043
- }).filter((note) => note.characterIds.includes(characterId)), clock(session.metadata.get().turns + 1)),
1044
- doneCues: (ids) => {
1045
- session.transaction(() => {
1046
- for (const id of ids) session.triggers.resolveNote(id, "done");
1047
- });
1048
- },
1049
- lapseNotes: (turn) => {
1050
- const { triggers } = settings();
1051
- session.lapseNotes(turn, {
1052
- beats: triggers.beatTurns,
1053
- cues: triggers.cueTurns
1054
- });
1055
- }
1056
- };
1057
- }
1058
- //#endregion
1059
- //#region src/host/clock/agenda.ts
1060
- const CURSOR = "agenda.cursor";
1061
- const ASKED = "agenda.asked";
1062
- /** At most this many characters are asked to be given a day at a time, so that it never floods the world author. */
1063
- const MAX_ASKED = 3;
1064
- /** How far ahead the characters are told about what comes next in their day. */
1065
- const NEXT_HORIZON = 240 * MINUTE;
1066
- /** What a character is shown of its own agenda at most. */
1067
- const SHOWN_ENGAGEMENTS = 4;
1068
- const SHOWN_GOALS = 3;
1069
- const keyOfCharacter$1 = (character) => character.sourceId ?? String(character.id);
1070
- /**
1071
- * Bring the days of the characters up to the story's time: those who are not in the player's scene go where their
1072
- * routine has them now, and take up what it has them doing, when the window they are in has changed since the last
1073
- * time. Characters in the scene stay: the game master is told what their day expects of them instead. It costs
1074
- * nothing but a look at each character's windows, however long the story was skipped.
1075
- */
1076
- function catchUpRoutines(session, zone, now, turn, ask) {
1077
- return session.transaction(() => {
1078
- const cursor = typeof session.metadata.getValue(CURSOR) === "number" ? session.metadata.getValue(CURSOR) : void 0;
1079
- if (cursor === now) return [];
1080
- const player = session.characters.list().find((character) => character.control === "player");
1081
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1082
- const moves = [];
1083
- const alreadyAsked = new Set(Array.isArray(session.metadata.getValue(ASKED)) ? session.metadata.getValue(ASKED) : []);
1084
- const asked = [];
1085
- for (const character of session.characters.list()) {
1086
- if (character.control === "player") continue;
1087
- const characterId = character.id;
1088
- const window = session.routines.list(characterId);
1089
- const here = session.placements.get("character", characterId);
1090
- const away = playerPlace === void 0 || here?.locationId !== playerPlace;
1091
- if (window.length === 0) {
1092
- if (ask && playerPlace !== void 0 && away && cursor !== void 0 && asked.length < MAX_ASKED && character.kind === "person" && character.tier !== "background" && !alreadyAsked.has(characterId)) {
1093
- session.consolidation.enqueue({
1094
- kind: "character",
1095
- subjectId: characterId,
1096
- note: "has no routine: give it a day (routines), as far as its role and the story imply",
1097
- turn
1098
- });
1099
- asked.push(characterId);
1100
- }
1101
- continue;
1102
- }
1103
- if (!away) continue;
1104
- const current = occurrenceAt(window, now, zone);
1105
- if (current === void 0) continue;
1106
- const before = cursor === void 0 ? void 0 : occurrenceAt(window, cursor, zone);
1107
- if (before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
1108
- const target = current.window;
1109
- if (target.locationId !== void 0 && (here?.locationId !== target.locationId || target.position !== void 0 && here.position !== target.position)) {
1110
- session.move(characterId, {
1111
- to: target.locationId,
1112
- ignoreExits: true,
1113
- ...target.position === void 0 ? {} : { position: target.position },
1114
- ...target.featureKey === void 0 ? {} : { featureKey: target.featureKey }
1115
- });
1116
- moves.push({
1117
- character: keyOfCharacter$1(character),
1118
- name: character.name,
1119
- to: session.locations.get(target.locationId)?.name ?? String(target.locationId),
1120
- activity: target.activity
1121
- });
1122
- }
1123
- if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
1124
- }
1125
- session.metadata.setValue(CURSOR, now);
1126
- if (asked.length > 0) session.metadata.setValue(ASKED, [...alreadyAsked, ...asked]);
1127
- return moves;
1128
- });
1129
- }
1130
- /** A character's agenda at an instant, with places by name and others by name. */
1131
- function agendaView(session, characterId, zone, now) {
1132
- const agenda = agendaAt(session, characterId, now, zone, {
1133
- horizon: NEXT_HORIZON,
1134
- engagements: SHOWN_ENGAGEMENTS,
1135
- goals: SHOWN_GOALS
1136
- });
1137
- const place = (id) => id === void 0 ? void 0 : session.locations.get(id)?.name;
1138
- const names = (ids) => ids.filter((id) => id !== characterId).map((id) => session.characters.get(id)?.name ?? String(id));
1139
- return {
1140
- zone,
1141
- ...agenda.now === void 0 ? {} : { now: {
1142
- activity: agenda.now.window.activity,
1143
- ...place(agenda.now.window.locationId) === void 0 ? {} : { place: place(agenda.now.window.locationId) },
1144
- until: agenda.now.endsAt,
1145
- interruptible: agenda.now.window.interruptible
1146
- } },
1147
- ...agenda.next === void 0 ? {} : { next: {
1148
- activity: agenda.next.window.activity,
1149
- ...place(agenda.next.window.locationId) === void 0 ? {} : { place: place(agenda.next.window.locationId) },
1150
- at: agenda.next.startsAt
1151
- } },
1152
- engagements: agenda.engagements.map(({ engagement, overdue }) => ({
1153
- title: engagement.title,
1154
- at: engagement.at,
1155
- ...place(engagement.locationId) === void 0 ? {} : { place: place(engagement.locationId) },
1156
- with: names(engagement.participants),
1157
- overdue
1158
- })),
1159
- goals: agenda.goals.map(({ intent, deadlineAt, overdue }) => ({
1160
- name: intent.name,
1161
- type: intent.type,
1162
- description: intent.description,
1163
- plan: intent.plan.slice(0, 3),
1164
- ...deadlineAt === void 0 ? {} : { deadline: deadlineAt },
1165
- overdue
1166
- }))
1167
- };
1168
- }
1169
- /** How soon ahead the game master is told of a window ending or a commitment falling due. */
1170
- const SOON = 30 * MINUTE;
1171
- const MAX_NOTES = 6;
1172
- /** An engagement that has been overdue for longer than this is not worth the game master's attention every turn. */
1173
- const STALE = 1440 * MINUTE;
1174
- function sceneAgenda(session, zone, now, moved) {
1175
- const player = session.characters.list().find((character) => character.control === "player");
1176
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1177
- 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));
1178
- const here = [];
1179
- for (const characterId of withPlayer) {
1180
- const windows = session.routines.list(characterId);
1181
- const current = occurrenceAt(windows, now, zone);
1182
- const upcoming = nextOccurrence(windows, now, zone, SOON);
1183
- const name = session.characters.get(characterId)?.name ?? String(characterId);
1184
- const place = current?.window.locationId === void 0 ? void 0 : session.locations.get(current.window.locationId);
1185
- if (current !== void 0 && current.window.locationId !== void 0 && current.window.locationId !== playerPlace) here.push({
1186
- name,
1187
- note: `its day says "${current.window.activity}"${place === void 0 ? "" : ` at ${place.name}`} now, yet it is here`
1188
- });
1189
- else if (current !== void 0 && current.endsAt - now <= SOON) here.push({
1190
- name,
1191
- note: `"${current.window.activity}" is due to end soon`
1192
- });
1193
- else if (current === void 0 && upcoming !== void 0) here.push({
1194
- name,
1195
- note: `"${upcoming.window.activity}" begins soon${upcoming.window.locationId === void 0 ? "" : ` at ${session.locations.get(upcoming.window.locationId)?.name ?? ""}`}`
1196
- });
1197
- }
1198
- const engagements = session.engagements.list({
1199
- status: "pending",
1200
- to: now + SOON
1201
- }).filter((engagement) => now - (engagement.until ?? engagement.at) < STALE).slice(0, MAX_NOTES).map((engagement) => ({
1202
- title: engagement.title,
1203
- at: engagement.at,
1204
- ...engagement.locationId === void 0 ? {} : { place: session.locations.get(engagement.locationId)?.name ?? "" },
1205
- with: engagement.participants.map((id) => session.characters.get(id)?.name ?? String(id)),
1206
- overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE)
1207
- }));
1208
- return {
1209
- zone,
1210
- moved,
1211
- here: here.slice(0, MAX_NOTES),
1212
- engagements
1213
- };
1214
- }
1215
- //#endregion
1216
- //#region src/host/clock/passage.ts
1217
- /** The start of a turn: the time, how long the player was away, and what the days of the characters make of it. */
1218
- function startTurn(session, config, turn, wall) {
1219
- const started = beginTurn(session, config, turn, wall);
1220
- const moved = catchUpRoutines(session, started.time.zone, started.time.now, turn, true);
1221
- return {
1222
- ...started,
1223
- agenda: sceneAgenda(session, started.time.zone, started.time.now, moved)
1224
- };
1225
- }
1226
- /** A round passes, and the characters outside the scene take up what their days have for the new time. */
1227
- function passRound(session, config, turn, round, wall, stated, minimum) {
1228
- const span = endRound(session, config, turn, round, wall, stated, minimum);
1229
- return {
1230
- ...span,
1231
- moved: catchUpRoutines(session, span.zone, span.to, turn, false)
1232
- };
1233
- }
1234
- /** Time is skipped, and the characters outside the scene take up what their days have for the new time. */
1235
- function skipAhead(session, config, turn, round, wall, request) {
1236
- const span = skipTime(session, config, turn, round, wall, request);
1237
- return {
1238
- ...span,
1239
- moved: catchUpRoutines(session, span.zone, span.to, turn, true)
1240
- };
1241
- }
1242
- /** What a character is told of its own agenda. */
1243
- function agendaFor(session, config, turn, wall, characterId) {
1244
- const time = readTime(session, config, turn, wall());
1245
- return agendaView(session, characterId, zoneOf(config), time.now);
1246
- }
1247
- //#endregion
1248
- //#region src/host/clock/offscene.ts
1249
- const HANDLED = "offscene.handled";
1250
- const keyOf = (character) => character.sourceId ?? String(character.id);
1251
- function handledKeys(session) {
1252
- const stored = session.metadata.getValue(HANDLED);
1253
- return new Set(Array.isArray(stored) ? stored.filter((entry) => typeof entry === "string") : []);
1254
- }
1255
- /** Remember that these were dealt with, so that they are not dealt with again. */
1256
- function markHandled(session, keys) {
1257
- session.metadata.setValue(HANDLED, [...handledKeys(session), ...keys].slice(-500));
1258
- }
1259
- /**
1260
- * What has fallen due for characters who are not with the player and who have not dealt with it yet: commitments
1261
- * whose time has come with everyone to do with them away from the scene, and goals whose deadline has passed.
1262
- * Oldest first.
1263
- */
1264
- function dueOffScene(session, zone, now, language = "en") {
1265
- const tr = translator(language);
1266
- const when = (instant) => describeWhen(instant, now, zone, language);
1267
- const handled = handledKeys(session);
1268
- const characters = session.characters.list();
1269
- const player = characters.find((character) => character.control === "player");
1270
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1271
- const away = (id) => playerPlace !== void 0 && session.placements.get("character", id)?.locationId !== playerPlace;
1272
- const agents = new Map(characters.filter((character) => character.control === "agent").map((character) => [character.id, character]));
1273
- const items = [];
1274
- for (const engagement of session.engagements.list({
1275
- status: "pending",
1276
- to: now + 1
1277
- })) {
1278
- const key = `e${engagement.id}`;
1279
- if (handled.has(key) || now < engagement.at + 1) continue;
1280
- const everyone = engagement.participants;
1281
- if (everyone.some((id) => !agents.has(id) || !away(id))) continue;
1282
- const place = engagement.locationId === void 0 ? void 0 : session.locations.get(engagement.locationId);
1283
- items.push({
1284
- key,
1285
- kind: "engagement",
1286
- at: engagement.at,
1287
- characters: everyone.map((id) => keyOf(agents.get(id))),
1288
- ...place === void 0 ? {} : { place: place.sourceId ?? String(place.id) },
1289
- text: [
1290
- `${place === void 0 ? tr("You were to {title}, at {when}", {
1291
- title: engagement.title,
1292
- when: when(engagement.at)
1293
- }) : tr("You were to {title} at {place}, at {when}", {
1294
- title: engagement.title,
1295
- place: place.name,
1296
- when: when(engagement.at)
1297
- })}${engagement.note === "" ? "" : tr(" ({note})", { note: engagement.note })}${tr(".")}`,
1298
- 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) }),
1299
- tr("It was with: {who}.", { who: everyone.map((id) => agents.get(id).name).join(tr(", ")) }),
1300
- tr("You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.")
1301
- ].join(" ")
1302
- });
1303
- }
1304
- for (const character of agents.values()) {
1305
- if (!away(character.id)) continue;
1306
- for (const goal of session.intents.list(character.id, { status: "active" })) {
1307
- const key = `g${goal.id}`;
1308
- let deadline;
1309
- try {
1310
- deadline = goal.deadline === void 0 ? void 0 : parseInstant(goal.deadline, zone);
1311
- } catch {
1312
- deadline = void 0;
1313
- }
1314
- if (handled.has(key) || deadline === void 0 || deadline >= now) continue;
1315
- items.push({
1316
- key,
1317
- kind: "goal",
1318
- at: deadline,
1319
- characters: [keyOf(character)],
1320
- text: `${tr("The time you had for \"{goal}\" has passed ({when}; it is {now} now)", {
1321
- goal: goal.name,
1322
- when: when(deadline),
1323
- now: when(now)
1324
- })}${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.")}`
1325
- });
1326
- }
1327
- }
1328
- return items.sort((a, b) => a.at - b.at);
1329
- }
1330
- //#endregion
1331
- //#region src/host/variables/describe.ts
1332
- /** What is tracked of a subject, in a line: `Health: hurt (2); Valence: unhappy (-0.4), usually even (0)`. */
1333
- function describeShown(shown) {
1334
- return shown.map(({ variable, value, baseline }) => {
1335
- const usual = baseline !== void 0 && baseline !== value ? `, usually ${describeValue(variable, baseline)}` : "";
1336
- return `${variable.name}: ${describeValue(variable, value)}${usual}`;
1337
- }).join("; ");
1338
- }
1339
- //#endregion
1340
- //#region src/host/orchestration/store.ts
1341
- /** The rules the session copied from its world when it started. */
1342
- function worldRules(session) {
1343
- const value = session.metadata.getValue(WORLD_RULES_KEY);
1344
- return Array.isArray(value) ? value.filter((rule) => typeof rule === "string") : [];
1345
- }
1346
- const keyOfCharacter = (character) => character.sourceId ?? String(character.id);
1347
- function placeOf(session, characterId) {
1348
- const placement = session.placements.get("character", characterId);
1349
- const location = placement === void 0 ? void 0 : session.locations.get(placement.locationId);
1350
- if (placement === void 0 || location === void 0) return void 0;
1351
- const feature = placement.featureKey === void 0 ? void 0 : location.features.find((candidate) => candidate.key === placement.featureKey);
1352
- return {
1353
- location,
1354
- position: placement.position,
1355
- ...feature === void 0 ? {} : { feature }
1356
- };
1357
- }
1358
- function castOf(session) {
1359
- return session.characters.list().map((character) => {
1360
- const state = session.characterStates.get(character.id);
1361
- const place = placeOf(session, character.id);
1362
- return {
1363
- key: keyOfCharacter(character),
1364
- character,
1365
- ...state === void 0 ? {} : { state },
1366
- ...place === void 0 ? {} : { place }
1367
- };
1368
- });
1369
- }
1370
- /** How much of what is in a container is told: a bag with fifty things in it is not recited. */
1371
- const SHOWN_CONTENTS = 5;
1372
- function viewOf(session, id, where) {
1373
- const item = session.items.get(id);
1374
- if (item === void 0) return void 0;
1375
- const inside = item.container?.state === "open" ? session.items.contents({
1376
- kind: "item",
1377
- id
1378
- }).filter((entry) => !entry.item.hidden).map((entry) => entry.item.quantity > 1 ? `${entry.item.quantity} ${entry.item.name}` : entry.item.name) : void 0;
1379
- return {
1380
- key: itemKey(item),
1381
- name: item.name,
1382
- quantity: item.quantity,
1383
- quality: item.quality,
1384
- notable: item.notable,
1385
- hidden: item.hidden,
1386
- ...item.container === void 0 ? {} : { state: item.container.state },
1387
- ...inside === void 0 || inside.length === 0 ? {} : { contents: [...inside.slice(0, SHOWN_CONTENTS), ...inside.length > SHOWN_CONTENTS ? [`and ${inside.length - SHOWN_CONTENTS} more`] : []] },
1388
- ...where === void 0 || where === "" ? {} : { where }
1389
- };
1390
- }
1391
- /** What lies in a place, notable things first; hidden things are included only when asked for. */
1392
- function itemsIn(session, locationId, withHidden) {
1393
- return session.items.contents({
1394
- kind: "location",
1395
- id: locationId
1396
- }).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) => {
1397
- const holder = entry.holding.holder;
1398
- const feature = holder.kind === "location" && holder.featureKey !== void 0 ? session.locations.get(locationId)?.features.find((candidate) => candidate.key === holder.featureKey)?.name : void 0;
1399
- const where = holder.kind === "location" ? [holder.position, feature === void 0 ? void 0 : `at ${feature}`].filter((part) => part !== void 0 && part !== "").join(", ") : "";
1400
- const view = viewOf(session, entry.item.id, where);
1401
- return view === void 0 ? [] : [view];
1402
- });
1403
- }
1404
- function carriedBy(session, characterId) {
1405
- return session.items.contents({
1406
- kind: "character",
1407
- id: characterId
1408
- }).sort((a, b) => Number(b.item.notable) - Number(a.item.notable) || a.item.id - b.item.id).flatMap((entry) => {
1409
- const holder = entry.holding.holder;
1410
- const view = viewOf(session, entry.item.id, holder.kind === "character" && holder.mode === "worn" ? `worn on the ${holder.slot}` : "carried");
1411
- return view === void 0 ? [] : [view];
1412
- });
1413
- }
1414
- function knowledgeOf(session, characterId, turn, visibleCharacters) {
1415
- observeSurroundings(session, characterId, turn);
1416
- const placement = session.placements.get("character", characterId);
1417
- 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);
1418
- const locations = session.knowledge.list(characterId, "location").flatMap((entry) => {
1419
- const place = session.locations.get(entry.subjectId);
1420
- return place === void 0 ? [] : [place.name];
1421
- });
1422
- const items = session.knowledge.list(characterId, "item").flatMap((entry) => {
1423
- const item = session.items.get(entry.subjectId);
1424
- return item === void 0 ? [] : [item.name];
1425
- });
1426
- const allExits = session.locations.allExits();
1427
- const routes = session.knowledge.list(characterId, "exit").flatMap((entry) => {
1428
- const exit = allExits.find((candidate) => candidate.id === entry.subjectId);
1429
- const from = exit === void 0 ? void 0 : session.locations.get(exit.fromId);
1430
- const to = exit === void 0 ? void 0 : session.locations.get(exit.toId);
1431
- return from === void 0 || to === void 0 ? [] : [`${from.name} -> ${to.name}`];
1432
- });
1433
- return {
1434
- characters: session.relationships.from(characterId).flatMap((relation) => {
1435
- const character = session.characters.get(relation.toId);
1436
- return character === void 0 ? [] : [character.name];
1437
- }),
1438
- factions: session.factionRelationships.from("character", characterId).filter((relation) => relation.toKind === "faction").flatMap((relation) => {
1439
- const faction = session.factions.get(relation.toId);
1440
- return faction === void 0 ? [] : [faction.name];
1441
- }),
1442
- locations,
1443
- items,
1444
- routes
1445
- };
1446
- }
1447
- function affiliationsOf(session, characterId) {
1448
- return session.factionMemberships.ofCharacter(characterId).flatMap((membership) => {
1449
- const faction = session.factions.get(membership.factionId);
1450
- if (faction === void 0) return [];
1451
- const relation = session.factionRelationships.get("character", characterId, "faction", faction.id);
1452
- const relationship = relation === void 0 ? void 0 : {
1453
- name: faction.name,
1454
- label: relation.label,
1455
- summary: relation.summary,
1456
- present: false,
1457
- familiarity: relation.familiarity,
1458
- trust: relation.trust,
1459
- affinity: relation.affinity,
1460
- tension: relation.tension
1461
- };
1462
- return [{
1463
- name: faction.name,
1464
- role: membership.role,
1465
- rank: membership.rank,
1466
- status: membership.status,
1467
- commitment: membership.commitment,
1468
- publicState: session.factionStates.get(faction.id)?.publicState ?? "",
1469
- goals: session.factionIntents.list(faction.id, { status: "active" }).map((intent) => intent.name),
1470
- ...relationship === void 0 ? {} : { relationship }
1471
- }];
1472
- });
1473
- }
1474
- function placeViewOf(session, locationId) {
1475
- const location = session.locations.get(locationId);
1476
- if (location === void 0) return void 0;
1477
- const here = new Set(session.placements.at(locationId, "character").map((placement) => placement.entityId));
1478
- return {
1479
- key: locationKey(location),
1480
- location,
1481
- exits: session.locations.exitsFrom(locationId).flatMap((exit) => {
1482
- const to = session.locations.get(exit.toId);
1483
- return to === void 0 ? [] : [{
1484
- key: locationKey(to),
1485
- name: to.name,
1486
- exit
1487
- }];
1488
- }),
1489
- here: castOf(session).filter((member) => here.has(member.character.id)),
1490
- items: itemsIn(session, locationId, false)
1491
- };
1492
- }
1493
- var DryRunDone = class extends Error {};
1494
- /** Do the changes in order inside a transaction that is always undone, so that a later change sees the earlier ones. */
1495
- function dryRunItems(session, entries) {
1496
- const problems = [];
1497
- const effects = [];
1498
- try {
1499
- session.transaction(() => {
1500
- for (const entry of entries) {
1501
- const character = session.characters.list().find((candidate) => keyOfCharacter(candidate) === entry.character);
1502
- const mine = [];
1503
- effects.push(mine);
1504
- if (character === void 0) {
1505
- problems.push(`${entry.character}: there is no such character`);
1506
- continue;
1507
- }
1508
- for (const spec of entry.changes) {
1509
- const planned = planItemChange(session, character.id, spec);
1510
- if (!planned.ok) {
1511
- problems.push(...planned.problems.map((problem) => `${entry.character}: cannot ${spec.action} ${spec.item}: ${problem}`));
1512
- break;
1513
- }
1514
- mine.push(applyItemPlan(session, planned.plan));
1515
- }
1516
- }
1517
- throw new DryRunDone();
1518
- });
1519
- } catch (error) {
1520
- if (!(error instanceof DryRunDone)) throw error;
1521
- }
1522
- return problems.length === 0 ? {
1523
- ok: true,
1524
- effects
1525
- } : {
1526
- ok: false,
1527
- problems
1528
- };
1529
- }
1530
- /** What a character can tell of itself and of those with it, in words. */
1531
- function trackedFor(session, characterId, presentIds) {
1532
- const character = session.characters.get(characterId);
1533
- return {
1534
- self: character === void 0 ? "" : describeShown(shownVariables(session, "character", characterId, keyOfCharacter(character), "self")),
1535
- others: presentIds.filter((id) => id !== characterId).flatMap((id) => {
1536
- const other = session.characters.get(id);
1537
- const text = other === void 0 ? "" : describeShown(shownVariables(session, "character", id, keyOfCharacter(other), "others"));
1538
- return other === void 0 || text === "" ? [] : [{
1539
- name: other.name,
1540
- text
1541
- }];
1542
- })
1543
- };
1544
- }
1545
- /** At most this many lines of what the story tracks are told to the game master at once. */
1546
- const MAX_TRACKED_LINES = 14;
1547
- /** What the story tracks, for the game master: everything, the scene first. */
1548
- function trackedLines(session) {
1549
- const player = session.characters.list().find((character) => character.control === "player");
1550
- const here = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
1551
- const near = (characterId) => here !== void 0 && session.placements.get("character", characterId)?.locationId === here ? 0 : 1;
1552
- const lines = [];
1553
- const world = describeShown(shownVariables(session, "world", 0, "world", "story"));
1554
- if (world !== "") lines.push(`the world: ${world}`);
1555
- if (here !== void 0) {
1556
- const place = session.locations.get(here);
1557
- const text = place === void 0 ? "" : describeShown(shownVariables(session, "location", here, locationKey(place), "story"));
1558
- if (place !== void 0 && text !== "") lines.push(`${place.name} (${locationKey(place)}): ${text}`);
1559
- for (const entry of session.items.contents({
1560
- kind: "location",
1561
- id: here
1562
- })) {
1563
- const text = describeShown(shownVariables(session, "item", entry.item.id, itemKey(entry.item), "story"));
1564
- if (text !== "") lines.push(`${entry.item.name} (${itemKey(entry.item)}): ${text}`);
1565
- }
1566
- }
1567
- for (const character of [...session.characters.list()].sort((a, b) => near(a.id) - near(b.id))) {
1568
- const text = describeShown(shownVariables(session, "character", character.id, keyOfCharacter(character), "story"));
1569
- if (text !== "") lines.push(`${character.name} (${keyOfCharacter(character)}): ${text}`);
1570
- }
1571
- return lines.slice(0, MAX_TRACKED_LINES);
1572
- }
1573
- function checkMove(session, characterKey, request) {
1574
- const character = session.characters.list().find((candidate) => keyOfCharacter(candidate) === characterKey);
1575
- if (character === void 0) return {
1576
- ok: false,
1577
- problems: [`there is no character "${characterKey}"`]
1578
- };
1579
- const to = session.locations.list().find((candidate) => locationKey(candidate) === request.location);
1580
- if (to === void 0) return {
1581
- ok: false,
1582
- problems: [`there is no place "${request.location}" (list_locations shows the keys)`]
1583
- };
1584
- const move = {
1585
- to: to.id,
1586
- ...request.position === void 0 ? {} : { position: request.position },
1587
- ...request.feature === void 0 ? {} : { featureKey: request.feature },
1588
- ...request.ignoreExits === true ? { ignoreExits: true } : {}
1589
- };
1590
- const planned = session.planKnownMove(character.id, move);
1591
- return planned.ok ? {
1592
- ok: true,
1593
- move,
1594
- plan: planned.plan,
1595
- to: {
1596
- key: locationKey(to),
1597
- name: to.name
1598
- },
1599
- ...request.position === void 0 ? {} : { position: request.position }
1600
- } : {
1601
- ok: false,
1602
- problems: planned.problems
1603
- };
1604
- }
1605
- function storeOf(session, folder, problem, queryVector, wall, prompt) {
1606
- const settings = () => liveSettings(folder, problem);
1607
- return {
1608
- story: session,
1609
- cast: () => castOf(session),
1610
- checkMove: (character, request) => checkMove(session, character, request),
1611
- place: (locationId) => placeViewOf(session, locationId),
1612
- settings,
1613
- text: (id, variables) => prompt(settings().prompts.language, id, variables),
1614
- rules: () => rulesOf(worldRules(session), settings().rules.own),
1615
- time: (turn) => readTime(session, settings().clock, turn, wall()),
1616
- beginTurn: (turn) => {
1617
- observeAsPlayer(session, turn);
1618
- return startTurn(session, settings().clock, turn, wall());
1619
- },
1620
- endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum),
1621
- skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request),
1622
- checkVariableChanges: (changes) => changes.flatMap((spec) => {
1623
- const planned = planVariableChange(session, spec);
1624
- return planned.ok ? [] : planned.problems;
1625
- }),
1626
- changeVariables: (turn, changes) => session.transaction(() => changes.map((spec) => changeVariable(session, spec, turn))),
1627
- trackedFor: (characterId, presentIds) => trackedFor(session, characterId, presentIds),
1628
- tracked: () => trackedLines(session),
1629
- dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now, languageOf(settings().prompts.language)),
1630
- markHandled: (keys) => {
1631
- markHandled(session, keys);
1632
- },
1633
- runTriggers: (turn, round) => {
1634
- const settings = liveSettings(folder, problem);
1635
- const { now, zone } = readTime(session, settings.clock, turn, wall());
1636
- return fireTriggers(session, {
1637
- settings,
1638
- turn,
1639
- round,
1640
- now,
1641
- zone,
1642
- problem
1643
- });
1644
- },
1645
- ...noteStore(session, () => liveSettings(folder, problem), (turn) => {
1646
- const { now, zone } = readTime(session, liveSettings(folder, problem).clock, turn, wall());
1647
- return {
1648
- now,
1649
- zone
1650
- };
1651
- }),
1652
- putNote: (note) => {
1653
- putNote(session, note);
1654
- },
1655
- addNote: (kind, turn, lines) => {
1656
- addToNote(session, kind, turn, lines);
1657
- },
1658
- recordActivity: (entry, detail) => {
1659
- if (detail !== void 0 && entry.run !== void 0) keepRunDetail(folder, entry.run, detail);
1660
- forgetRunDetails(folder, recordActivity(session, entry));
1661
- },
1662
- notes: () => readNotes(session),
1663
- clearNotes: () => {
1664
- clearNotes(session);
1665
- },
1666
- agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId),
1667
- commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items }) => {
1668
- session.characterStates.update(character, patch);
1669
- const effects = (items ?? []).map((spec) => changeItem(session, character, spec));
1670
- if (move !== void 0) session.move(character, move);
1671
- return effects;
1672
- })),
1673
- checkItemChanges: (entries) => dryRunItems(session, entries),
1674
- carried: (characterId) => carriedBy(session, characterId),
1675
- knowledge: (characterId, turn, visibleCharacters) => knowledgeOf(session, characterId, turn, visibleCharacters),
1676
- affiliations: (characterId) => affiliationsOf(session, characterId),
1677
- itemsAt: (locationId, withHidden = false) => itemsIn(session, locationId, withHidden),
1678
- completeTurn: () => {
1679
- session.metadata.recordTurn();
1680
- },
1681
- queueCommit: (record) => {
1682
- session.pendingCommits.enqueue(record.turn, record.round, JSON.parse(JSON.stringify(record)));
1683
- },
1684
- pendingCommits: () => session.pendingCommits.list().map((entry) => entry.payload),
1685
- completeCommits: (rounds) => {
1686
- session.transaction(() => {
1687
- session.events.seal();
1688
- session.pendingCommits.complete(rounds);
1689
- });
1690
- },
1691
- queryVector
1692
- };
1693
- }
1694
- /** Opens the store of the roleplay session behind a chat; a chat that is not one gets none. */
1695
- function storesOf(state, sessionsDir, problem = () => void 0, queryVector = () => Promise.resolve(void 0), wall = Date.now, prompt = (language, id, variables) => shippedText(id, language, variables)) {
1696
- return (chat) => {
1697
- const id = roleplaySessionOf(chat);
1698
- if (id === void 0) return void 0;
1699
- try {
1700
- 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));
1701
- } catch {
1702
- return;
1703
- }
1704
- };
1705
- }
1706
- //#endregion
1707
- //#region src/shared/roll.ts
1708
- /** The player rolls dice before acting: `/roll 2d6+1 pick the lock`. The dice are then part of what the game master judges. */
1709
- const ROLL_COMMAND = /^\s*\/roll(?=\s|$)\s*(\S*)\s*([\s\S]*)$/i;
1710
- /** The roll in a player's message, or nothing when the message does not start with `/roll`. The notation may be empty, and is then refused. */
1711
- function parseRoll(text) {
1712
- const match = ROLL_COMMAND.exec(text);
1713
- return match === null ? void 0 : {
1714
- expression: match[1] ?? "",
1715
- reason: (match[2] ?? "").trim()
1716
- };
1717
- }
1718
- //#endregion
1719
- //#region src/host/orchestration/hooks.ts
1720
- const notice = (text) => createUserMessage({
1721
- content: [{
1722
- type: "text",
1723
- text
1724
- }],
1725
- source: { kind: "roleplay" }
1726
- });
1727
- /** The turn of the game master of a roleplay chat; characters and other chats have none. */
1728
- function ownerOf(agent, turn) {
1729
- if (agent.session.header.origin === "subagent") return void 0;
1730
- return roleplaySessionOf(agent.session.id) === void 0 ? void 0 : {
1731
- chat: agent.session.id,
1732
- turn
1733
- };
1734
- }
1735
- /** 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. */
1736
- const PREVIEW_SHOWN = Symbol.for("dsh-agentic-roleplay.preview-tool");
1737
- /** Registers the preview tool on the agent of a chat that shows one, once, and withdraws it when the setting is turned off. */
1738
- function previewToggle(tool) {
1739
- return (agent, enabled) => {
1740
- const holder = agent;
1741
- const withdraw = holder[PREVIEW_SHOWN];
1742
- if (enabled && withdraw === void 0) try {
1743
- holder[PREVIEW_SHOWN] = agent.ctx.tools.register(tool);
1744
- } catch (error) {
1745
- if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
1746
- holder[PREVIEW_SHOWN] = () => void 0;
1747
- }
1748
- else if (!enabled && withdraw !== void 0) {
1749
- delete holder[PREVIEW_SHOWN];
1750
- withdraw();
1751
- }
1752
- };
1753
- }
1754
- /** Where the withdrawals of an agent's optional tools are kept, by tool name: on the agent, so that a reloaded plugin still finds what its earlier self registered. */
1755
- const OPTIONAL_SHOWN = Symbol.for("dsh-agentic-roleplay.optional-tools");
1756
- /** Puts an agent's optional tools in line with the switches: registers the ones that are on and not yet there, withdraws the ones that are off. */
1757
- function optionalToolSwitch(tools) {
1758
- return (agent, enabled) => {
1759
- const holder = agent;
1760
- const shown = holder[OPTIONAL_SHOWN] ??= /* @__PURE__ */ new Map();
1761
- for (const tool of tools) {
1762
- const withdraw = shown.get(tool.name);
1763
- if (enabled(tool.name) && withdraw === void 0) try {
1764
- shown.set(tool.name, agent.ctx.tools.register(tool));
1765
- } catch (error) {
1766
- if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
1767
- shown.set(tool.name, () => void 0);
1768
- }
1769
- else if (!enabled(tool.name) && withdraw !== void 0) {
1770
- shown.delete(tool.name);
1771
- withdraw();
1772
- }
1773
- }
1774
- };
1775
- }
1776
- /** Where an agent's withdrawal of the external tools it was not given is kept: on the agent, so that a reloaded plugin still finds what its earlier self set. */
1777
- const EXTERNAL_LIMIT = Symbol.for("dsh-agentic-roleplay.external-limit");
1778
- /**
1779
- * Takes away from an agent the tools other plugins registered for everyone that it was not given. A story gives the game master such tools (a file or
1780
- * shell tool, an MCP server's) by switching them on; without it the agent has none of them. The limit follows the settings as they change.
1781
- */
1782
- function externalToolLimit(agent, withheld) {
1783
- const holder = agent;
1784
- const key = [...withheld].sort().join("\n");
1785
- const current = holder[EXTERNAL_LIMIT];
1786
- if (current?.key === key) return;
1787
- current?.lift();
1788
- delete holder[EXTERNAL_LIMIT];
1789
- if (withheld.length > 0) holder[EXTERNAL_LIMIT] = {
1790
- key,
1791
- lift: agent.ctx.tools.restrict({ deny: [...withheld] })
1792
- };
1793
- }
1794
- /**
1795
- * The listeners of a roleplay preset. Preset listeners are shared by every chat
1796
- * that uses the preset and also hear the agents that chat spawns, so each one
1797
- * first checks that it is looking at the game master of a roleplay chat.
1798
- */
1799
- function installHooks(ctx, deps) {
1800
- const { engine, boundaries, stores, timelines, previewTool } = deps;
1801
- const showPreviewTool = previewToggle(previewTool);
1802
- const showOptionalTools = optionalToolSwitch(deps.optionalTools ?? []);
1803
- /** The tools of the game master as the chat's settings say: its optional ones, and none of other plugins' that it was not given. */
1804
- const applyTools = (agent, store) => {
1805
- const { tools } = store.settings();
1806
- showOptionalTools(agent, (tool) => toolEnabled(tools, "gameMaster", tool));
1807
- externalToolLimit(agent, externalWithheld(agent.ctx.tools, tools, "gameMaster"));
1808
- };
1809
- ctx.on("agent/created", ({ agent }) => {
1810
- const owner = ownerOf(agent, 0);
1811
- const store = owner === void 0 ? void 0 : stores(owner.chat);
1812
- if (store !== void 0) applyTools(agent, store);
1813
- });
1814
- ctx.on("session/event", (session, event) => {
1815
- if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
1816
- timelines.ended(session.id, session, event.seq);
1817
- });
1818
- ctx.on("agent/created", async ({ agent }) => {
1819
- const { header } = agent.session;
1820
- if (header.origin === "subagent" || !header.isSeeded || header.parentSession === void 0) return;
1821
- if (roleplaySessionOf(agent.session.id) === void 0 || roleplaySessionOf(header.parentSession) === void 0) return;
1822
- await timelines.adopt(agent.session.id, header.parentSession, agent.session.inheritedEventCount - 1, agent);
1823
- });
1824
- ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
1825
- const owner = ownerOf(agent, turn);
1826
- if (owner === void 0) return;
1827
- const missing = engine.missing(owner);
1828
- if (missing === void 0) return;
1829
- if (!engine.object(owner)) {
1830
- ctx.logger.warn(`roleplay: ${owner.chat} ended turn ${turn} without finishing it (${missing})`);
1831
- return;
1832
- }
1833
- agent.steer(notice(`You may not end the turn yet: ${missing}.`));
1834
- });
1835
- ctx.on("agent/pre-step", async (payload, next) => {
1836
- const decision = await next();
1837
- const owner = ownerOf(payload.agent, payload.turn);
1838
- const store = owner === void 0 ? void 0 : stores(owner.chat);
1839
- if (owner !== void 0 && store !== void 0) {
1840
- showPreviewTool(payload.agent, store.settings().preview.enabled);
1841
- applyTools(payload.agent, store);
1842
- }
1843
- if (decision.kind !== "enter" || payload.step !== 1) return decision;
1844
- if (owner === void 0 || store === void 0) return decision;
1845
- const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
1846
- await timelines.begin(owner.chat, payload.turn, text);
1847
- const cast = store.cast();
1848
- const ooc = parseOoc(text);
1849
- const verdict = ooc === void 0 ? boundaries().inputValidator.validate({
1850
- text,
1851
- turn: payload.turn,
1852
- cast
1853
- }) : { ok: true };
1854
- if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
1855
- else if (ooc === void 0) engine.expectJudgement(owner);
1856
- const queryVector = await store.queryVector(ooc?.request ?? text);
1857
- store.clearNotes();
1858
- store.lapseNotes(payload.turn);
1859
- const { time, away, agenda } = store.beginTurn(payload.turn);
1860
- const tr = translator(languageOf(store.settings().prompts.language));
1861
- if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => tr("{name} went to {place}.", {
1862
- name: move.name,
1863
- place: move.to
1864
- })));
1865
- const world = {
1866
- happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
1867
- names: cue.names.join(tr(" and ")),
1868
- text: cue.text
1869
- }))]),
1870
- beats: store.pendingBeats(),
1871
- upcoming: store.upcoming(payload.turn)
1872
- };
1873
- const tracked = store.tracked();
1874
- const lines = [boundaries().sceneContext.scene({
1875
- ...tracked.length === 0 ? {} : { tracked },
1876
- time: {
1877
- now: time,
1878
- agenda,
1879
- ...away === void 0 ? {} : { away }
1880
- },
1881
- ...world.happened.length === 0 && world.beats.length === 0 && world.upcoming.length === 0 ? {} : { world },
1882
- cast,
1883
- turn: payload.turn,
1884
- input: text,
1885
- story: store.story,
1886
- items: {
1887
- at: (locationId) => store.itemsAt(locationId, true),
1888
- carried: (characterId) => store.carried(characterId)
1889
- },
1890
- language: store.settings().prompts.language,
1891
- ...queryVector === void 0 ? {} : { queryVector }
1892
- })];
1893
- const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
1894
- if (pacing !== void 0) lines.push(describePacingAdvice(pacing));
1895
- else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
1896
- const rules = store.rules();
1897
- if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
1898
- const wanted = ooc === void 0 ? parseRoll(text) : void 0;
1899
- if (wanted !== void 0) try {
1900
- const made = rollPlain(wanted.expression);
1901
- const roll = store.story.dice.record({
1902
- turn: payload.turn,
1903
- expression: made.expression,
1904
- faces: made.faces,
1905
- kept: made.kept,
1906
- modifier: made.modifier,
1907
- total: made.total,
1908
- value: made.total,
1909
- reason: wanted.reason === "" ? tr("the player's roll") : wanted.reason,
1910
- by: "player"
1911
- });
1912
- lines.push(tr("The player rolled {dice} ({reason}) and got {total}: dice {faces}. This is a fact, decided by the dice: take it into account when you judge the attempt and decide what happens.", {
1913
- dice: roll.expression,
1914
- reason: roll.reason,
1915
- total: roll.total,
1916
- faces: `[${roll.faces.join(", ")}]`
1917
- }));
1918
- } catch (error) {
1919
- engine.skip(owner);
1920
- lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
1921
- }
1922
- if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
1923
- if (ooc !== void 0 && ooc.request === "") {
1924
- engine.skip(owner);
1925
- lines.push(store.text("roleplay/ooc-empty", { command: ooc.question ? "/ask" : "/ooc" }));
1926
- }
1927
- if (!verdict.ok) {
1928
- engine.skip(owner);
1929
- lines.push(store.text("roleplay/input-refused", { reason: verdict.reason }));
1930
- }
1931
- return {
1932
- ...decision,
1933
- messages: [...decision.messages, notice(lines.join("\n\n"))]
1934
- };
1935
- });
1936
- }
1937
- //#endregion
1938
935
  //#region src/host/orchestration/prompt.ts
1939
936
  const PROTOCOL_SECTION = "roleplay:protocol";
1940
937
  const PERSONA_SECTION = "roleplay:persona";
@@ -2418,7 +1415,7 @@ async function askCharacters(deps, owner, number, keys, cast, state, run, signal
2418
1415
  language: store?.settings().prompts.language ?? "en",
2419
1416
  turn: owner.turn,
2420
1417
  ...away ? { away: true } : {},
2421
- lookup: store?.settings().memory.lookup ?? false,
1418
+ lookup: store === void 0 ? false : store.settings().memory.lookup && toolEnabled(store.settings().tools, "characters", "recall_my_memories"),
2422
1419
  text: (id, variables) => deps.storeOf(owner).text(id, variables),
2423
1420
  ...time === void 0 ? {} : { time },
2424
1421
  ...agenda === void 0 ? {} : { agenda },
@@ -2614,6 +1611,118 @@ function recordRound(store, owner, state, fire) {
2614
1611
  };
2615
1612
  }
2616
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
2617
1726
  //#region src/host/orchestration/turn-text.ts
2618
1727
  /**
2619
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
@@ -2872,7 +1981,7 @@ var TurnEngine = class {
2872
1981
  const state = this.stateFor(owner);
2873
1982
  if (state.ooc?.question !== true) throw new Error("this turn is not an out-of-character question: there is nothing to answer");
2874
1983
  if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
2875
- 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();
2876
1985
  if (text === "") throw new Error("the answer is empty");
2877
1986
  if (state.ooc.ruling !== void 0) throw new Error("this question was already answered");
2878
1987
  state.ooc.ruling = {
@@ -2883,45 +1992,6 @@ var TurnEngine = class {
2883
1992
  state.phase = "between";
2884
1993
  return state.ooc.ruling;
2885
1994
  }
2886
- /** 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. */
2887
- async askedRequest(owner, question, signal) {
2888
- const store = this.storeOf(owner);
2889
- const cast = store.cast();
2890
- const member = cast.find((candidate) => candidate.character.control === "player");
2891
- if (member === void 0) throw new Error("there is no player's character to answer for");
2892
- const queryVector = await store.queryVector(question, signal);
2893
- const memories = await this.boundaries().recaller.recall({
2894
- member,
2895
- situation: question,
2896
- turn: owner.turn,
2897
- policy: store.settings().memory,
2898
- ...queryVector === void 0 ? {} : { queryVector }
2899
- }, store.story, signal);
2900
- const place = member.place === void 0 ? void 0 : store.place(member.place.location.id);
2901
- const company = place === void 0 ? cast : place.here;
2902
- const relationships = knownRelationships(member, company, question, cast, store);
2903
- const carrying = store.carried(member.character.id);
2904
- const affiliations = store.affiliations(member.character.id);
2905
- const tracked = store.trackedFor(member.character.id, company.map((entry) => entry.character.id));
2906
- return {
2907
- member,
2908
- cast,
2909
- situation: question,
2910
- attempt: 1,
2911
- language: store.settings().prompts.language,
2912
- turn: owner.turn,
2913
- lookup: false,
2914
- text: (id, variables) => store.text(id, variables),
2915
- time: store.time(owner.turn),
2916
- knowledge: store.knowledge(member.character.id, owner.turn, company.map((entry) => entry.character.id)),
2917
- ...tracked.self === "" && tracked.others.length === 0 ? {} : { tracked },
2918
- ...place === void 0 ? {} : { place },
2919
- ...relationships.length === 0 ? {} : { relationships },
2920
- ...carrying.length === 0 ? {} : { carrying },
2921
- ...affiliations.length === 0 ? {} : { affiliations },
2922
- ...memories.length === 0 ? {} : { memories }
2923
- };
2924
- }
2925
1995
  /**
2926
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
2927
1997
  * what the player is told. Either way the turn goes on to its output; only a legal ruling lets the command change anything.
@@ -3253,78 +2323,15 @@ var TurnEngine = class {
3253
2323
  return await this.deliver(owner, state, typed, false, run);
3254
2324
  }
3255
2325
  /**
3256
- * The game master asks for something to be made up (a place the story has gone to, someone who has
3257
- * joined): the world author decides whether the story genuinely needs it, and makes it or says why not.
3258
- * The world may be closed, and only so many things may be made up in a turn.
3259
- * @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.
3260
2328
  */
3261
2329
  async expand(owner, input, signal) {
3262
- const state = this.stateFor(owner);
3263
- 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");
3264
- const blocked = oocBlock(state);
3265
- if (blocked !== void 0) throw new Error(blocked);
3266
- const need = AUTHORING_NEEDS.find((candidate) => candidate === input.need);
3267
- if (need === void 0) throw new Error(`"${input.need}" is not a reason to make something up; the reasons are: ${AUTHORING_NEEDS.join(", ")}`);
3268
- const what = input.what.trim();
3269
- if (what === "") throw new Error("say what is needed, from what the story has established: who or where, and why now");
3270
- const store = this.storeOf(owner);
3271
- const { authoring } = store.settings();
3272
- if (!authoring.enabled) throw new Error("this world is closed: nothing can be made up in it");
3273
- const made = store.story.consolidation.createdIn(owner.turn).length;
3274
- 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`);
3275
- return await this.boundaries().author.create({
3276
- chat: owner.chat,
3277
- turn: owner.turn,
3278
- need,
3279
- what,
3280
- store
3281
- }, signal);
2330
+ return await expandWorld(this.boundaries(), this.storeOf(owner), this.stateFor(owner), owner, input, signal);
3282
2331
  }
3283
- /**
3284
- * 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
3285
- * (a place, someone's hands, a container; the player's place when it says nothing), with no world author asked.
3286
- * @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.
3287
- */
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. */
3288
2333
  introduce(owner, input) {
3289
- const state = this.stateFor(owner);
3290
- 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");
3291
- const blocked = oocBlock(state);
3292
- if (blocked !== void 0) throw new Error(blocked);
3293
- const name = input.name.trim();
3294
- if (name === "") throw new Error("name the thing");
3295
- const store = this.storeOf(owner);
3296
- const { authoring } = store.settings();
3297
- if (!authoring.enabled) throw new Error("this world is closed: nothing can be made up in it");
3298
- const kept = store.story.consolidation.createdIn(owner.turn).filter((entry) => entry.kind === "item").length;
3299
- 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`);
3300
- if ([
3301
- input.at,
3302
- input.heldBy,
3303
- input.inside
3304
- ].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");
3305
- const here = store.cast().find((member) => member.character.control === "player")?.place?.location;
3306
- 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) } };
3307
- 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)");
3308
- const key = uniqueKey(slug(name, "thing"), new Set(store.story.items.list().map((item) => item.sourceId).filter((entry) => entry !== void 0)));
3309
- store.story.edit({
3310
- turn: owner.turn,
3311
- items: [{
3312
- key,
3313
- name,
3314
- ...input.description === void 0 || input.description.trim() === "" ? {} : { description: input.description.trim() },
3315
- ...input.quantity === void 0 ? {} : { quantity: input.quantity },
3316
- ...input.quality === void 0 || input.quality.trim() === "" ? {} : { quality: input.quality.trim() },
3317
- ...input.notable === void 0 ? {} : { notable: input.notable },
3318
- ...input.hidden === void 0 ? {} : { hidden: input.hidden },
3319
- ...placed,
3320
- note: "introduced by the game master"
3321
- }]
3322
- });
3323
- return {
3324
- key,
3325
- name,
3326
- where: "heldBy" in placed ? `held by ${placed.heldBy}` : "inside" in placed ? `inside ${placed.inside}` : `at ${placed.at.location}`
3327
- };
2334
+ return introduceThing(this.storeOf(owner), this.stateFor(owner), owner, input);
3328
2335
  }
3329
2336
  /** Whether made-up characters and places are waiting to be fitted into the world. */
3330
2337
  waitingToFit(owner) {