@dsh-agentic-roleplay/core 0.3.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/lib/{preset-ClQm7KPQ.js → authoring-tools-C_8ClUkP.js} +542 -261
  2. package/lib/authoring.js +7 -5
  3. package/lib/{child-CFjnaTZt.js → child-DsixtqTw.js} +94 -2
  4. package/lib/client.js +16938 -14212
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/doctor.js +2 -4
  8. package/lib/{gallery-DIEgETzU.js → gallery-CDYKJf_O.js} +2 -2
  9. package/lib/{generator-DJ48HxPI.js → generator-BR1ugzln.js} +2 -2
  10. package/lib/{deliver-Cl6bjp7g.js → hooks-B2EhBS_-.js} +1884 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +1200 -242
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/lorebook-author-tools-C-o0t4dL.js +694 -0
  15. package/lib/lorebook-authoring.js +69 -0
  16. package/lib/{settings-CA6icLL_.js → narration-BT9uvQry.js} +145 -2
  17. package/lib/orchestration.js +34 -21
  18. package/lib/{pack-jail-ClMpVc__.js → pack-jail-soI-In96.js} +170 -12
  19. package/lib/{packs-BC2A3geF.js → packs-CJPSe5LI.js} +7 -4
  20. package/lib/{presenter-agent-DnNEG_Mn.js → presenter-agent-Gu34bZwd.js} +6 -6
  21. package/lib/preset-3zn8xme7.js +242 -0
  22. package/lib/{preset-author-tools-Dibp-LY9.js → preset-author-tools-C-X8G40s.js} +24 -18
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-DNjNxQL5.js → presets-C3mhqqfz.js} +50 -28
  25. package/lib/{reflection-Bju_LPFn.js → reflection-Btsj0ZLh.js} +51 -17
  26. package/package.json +3 -2
  27. package/packs/scene/map.html +1 -0
  28. package/packs/scene/strip.html +1 -0
  29. package/prompts/en/import/lorebook.md +8 -0
  30. package/prompts/en/import/style.md +1 -0
  31. package/prompts/en/lorebook/persona.md +1 -0
  32. package/prompts/en/lorebook/procedure.md +1 -0
  33. package/prompts/en/lorebook/welcome.md +1 -0
  34. package/prompts/en/preset/persona.md +1 -1
  35. package/prompts/en/preset/procedure.md +1 -1
  36. package/prompts/en/roleplay/character-lookup.md +1 -0
  37. package/prompts/en/roleplay/game-master.md +1 -1
  38. package/prompts/en/world/procedure.md +1 -1
  39. package/prompts/zh/import/lorebook.md +8 -0
  40. package/prompts/zh/import/style.md +1 -0
  41. package/prompts/zh/lorebook/persona.md +1 -0
  42. package/prompts/zh/lorebook/procedure.md +1 -0
  43. package/prompts/zh/lorebook/welcome.md +1 -0
  44. package/prompts/zh/preset/persona.md +1 -1
  45. package/prompts/zh/preset/procedure.md +1 -1
  46. package/prompts/zh/roleplay/character-lookup.md +1 -0
  47. package/prompts/zh/roleplay/game-master.md +1 -1
  48. package/prompts/zh/world/procedure.md +1 -1
  49. package/lib/hooks-DdO_tNhu.js +0 -1060
  50. package/lib/language-BgyxtB2h.js +0 -38
  51. package/lib/load-Clkl0T7C.js +0 -486
  52. package/lib/narration-DK2kiIjE.js +0 -141
@@ -1,1060 +0,0 @@
1
- import { r as roleplaySessionOf } from "./access-EbNdZFbk.js";
2
- import { a as WORLD_RULES_KEY, o as rulesOf } from "./settings-CA6icLL_.js";
3
- import { y as shippedText } from "./load-Clkl0T7C.js";
4
- import { A as observeAsPlayer, C as parseOoc, E as clearNotes, F as describeWhen, H as languageOf, I as endRound, L as readTime, N as beginTurn, O as putNote, R as skipTime, T as addToNote, U as translator, _ as pacingAdvice, a as forgetRunDetails, f as externalWithheld, g as describePacingAdvice, j as observeSurroundings, k as readNotes, l as recordActivity, o as keepRunDetail, r as addUsage, t as deliverNow, v as plotAuthorNeeded, w as toolEnabled, z as zoneOf } from "./deliver-Cl6bjp7g.js";
5
- import { a as liveSettings } from "./narration-DK2kiIjE.js";
6
- import { o as tokensOf } from "./child-CFjnaTZt.js";
7
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
8
- import { ENGAGEMENT_GRACE, MINUTE, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, describeDuration, describeInstant, describeValue, inAudience, itemKey, locationKey, nextOccurrence, occurrenceAt, parseInstant, planItemChange, planVariableChange, rollPlain, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
9
- //#region src/host/triggers/judged.ts
10
- const KEY = "triggers.judged";
11
- function readVerdicts(session) {
12
- const stored = session.metadata.getValue(KEY);
13
- if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
14
- const verdicts = {};
15
- for (const [statement, value] of Object.entries(stored)) {
16
- const verdict = value;
17
- if (typeof verdict === "object" && verdict !== null && typeof verdict.holds === "boolean" && typeof verdict.turn === "number") verdicts[statement] = {
18
- holds: verdict.holds,
19
- turn: verdict.turn
20
- };
21
- }
22
- return verdicts;
23
- }
24
- /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
25
- function writeVerdicts(session, verdicts, keep) {
26
- session.metadata.setValue(KEY, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
27
- }
28
- /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
29
- const verdictReader = (session) => {
30
- const verdicts = readVerdicts(session);
31
- return (statement) => verdicts[statement]?.holds === true;
32
- };
33
- //#endregion
34
- //#region src/host/triggers/notes.ts
35
- /** 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. */
36
- function fireTriggers(session, input) {
37
- const { settings, turn, round, now, zone, problem } = input;
38
- if (!settings.triggers.enabled) return { fired: [] };
39
- const before = Math.max(0, ...session.triggers.notes().map((note) => note.id));
40
- const run = session.runTriggers({
41
- turn,
42
- round,
43
- now,
44
- zone,
45
- maxFires: settings.triggers.maxFires,
46
- judged: verdictReader(session)
47
- });
48
- for (const failure of run.failed) problem(`the trigger "${failure.trigger.key}" could not fire and is given up: ${failure.problem}`);
49
- const names = new Map(session.characters.list().map((character) => [character.id, character.name]));
50
- const fresh = session.triggers.notes({ status: "pending" }).filter((note) => note.id > before);
51
- const told = new Map(deliverNow(session, fresh, {
52
- now,
53
- zone
54
- }).map((entry) => [entry.id, entry.text]));
55
- return { fired: run.fired.map((fired) => ({
56
- name: fired.trigger.name,
57
- events: fired.events,
58
- cues: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "cue" && told.has(note.id)).map((note) => ({
59
- names: note.characterIds.flatMap((id) => names.get(id) ?? []),
60
- text: told.get(note.id)
61
- })),
62
- beats: fresh.filter((note) => note.triggerId === fired.trigger.id && note.kind === "beat" && told.has(note.id)).map((note) => ({
63
- id: note.id,
64
- text: told.get(note.id)
65
- }))
66
- })) };
67
- }
68
- /** When something is to happen, as it is told: the date and how far off it is. */
69
- function whenText(at, clock) {
70
- if (at === void 0) return void 0;
71
- return `${describeInstant(at, clock.zone)}${at > clock.now ? `, in ${describeDuration(at - clock.now)}` : ""}`;
72
- }
73
- function whoKnows(session, announcement) {
74
- const { audience } = announcement;
75
- if (audience === "everyone") return "everyone";
76
- if ("place" in audience) return `whoever is at ${session.locations.list().find((place) => locationKey(place) === audience.place)?.name ?? audience.place}`;
77
- return audience.characters.map((key) => session.characters.list().find((entry) => (entry.sourceId ?? String(entry.id)) === key)?.name ?? key).join(", ");
78
- }
79
- /** At most this many announcements are told to one character at once: soonest first. */
80
- const MAX_UPCOMING_FOR_CHARACTER = 3;
81
- /** 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. */
82
- function noteStore(session, settings, clock) {
83
- return {
84
- upcoming: (turn) => {
85
- const now = clock(turn);
86
- return announcements(session, now).map((entry) => {
87
- const when = whenText(entry.at, now);
88
- return {
89
- text: entry.text,
90
- who: whoKnows(session, entry),
91
- ...when === void 0 ? {} : { when }
92
- };
93
- });
94
- },
95
- upcomingFor: (characterId, turn) => {
96
- const now = clock(turn);
97
- return announcements(session, now).filter((entry) => inAudience(session, entry.audience, characterId)).slice(0, MAX_UPCOMING_FOR_CHARACTER).map((entry) => {
98
- const when = whenText(entry.at, now);
99
- return {
100
- text: entry.text,
101
- ...when === void 0 ? {} : { when }
102
- };
103
- });
104
- },
105
- pendingBeats: () => deliverNow(session, session.triggers.notes({
106
- status: "pending",
107
- kind: "beat"
108
- }), clock(session.metadata.get().turns + 1)),
109
- resolveBeats: (ids) => {
110
- const pending = new Set(session.triggers.notes({
111
- status: "pending",
112
- kind: "beat"
113
- }).map((note) => note.id));
114
- const unknown = ids.filter((id) => !pending.has(id));
115
- 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`);
116
- session.transaction(() => {
117
- for (const id of ids) session.triggers.resolveNote(id, "done");
118
- });
119
- },
120
- cuesFor: (characterId) => deliverNow(session, session.triggers.notes({
121
- status: "pending",
122
- kind: "cue"
123
- }).filter((note) => note.characterIds.includes(characterId)), clock(session.metadata.get().turns + 1)),
124
- doneCues: (ids) => {
125
- session.transaction(() => {
126
- for (const id of ids) session.triggers.resolveNote(id, "done");
127
- });
128
- },
129
- lapseNotes: (turn) => {
130
- const { triggers } = settings();
131
- session.lapseNotes(turn, {
132
- beats: triggers.beatTurns,
133
- cues: triggers.cueTurns
134
- });
135
- }
136
- };
137
- }
138
- //#endregion
139
- //#region src/host/clock/agenda.ts
140
- const CURSOR = "agenda.cursor";
141
- const ASKED = "agenda.asked";
142
- /** Characters on their way to the place their day has them at, by character id: they get there when the way has taken as long as it takes. */
143
- const TRAVEL = "agenda.travel";
144
- /** At most this many characters are asked to be given a day at a time, so that it never floods the world author. */
145
- const MAX_ASKED = 3;
146
- /** How far ahead the characters are told about what comes next in their day. */
147
- const NEXT_HORIZON = 240 * MINUTE;
148
- /** What a character is shown of its own agenda at most. */
149
- const SHOWN_ENGAGEMENTS = 4;
150
- const SHOWN_GOALS = 3;
151
- const keyOfCharacter$1 = (character) => character.sourceId ?? String(character.id);
152
- /**
153
- * Bring the days of the characters up to the story's time: those who are not in the player's scene go where their
154
- * routine has them now, and take up what it has them doing, when the window they are in has changed since the last
155
- * time. Characters in the scene stay: the game master is told what their day expects of them instead. It costs
156
- * nothing but a look at each character's windows, however long the story was skipped.
157
- */
158
- function catchUpRoutines(session, zone, now, turn, ask) {
159
- return session.transaction(() => {
160
- const cursor = typeof session.metadata.getValue(CURSOR) === "number" ? session.metadata.getValue(CURSOR) : void 0;
161
- if (cursor === now) return [];
162
- const player = session.characters.list().find((character) => character.control === "player");
163
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
164
- const moves = [];
165
- const stored = session.metadata.getValue(TRAVEL);
166
- const journeys = typeof stored === "object" && stored !== null && !Array.isArray(stored) ? { ...stored } : {};
167
- const arrive = (character, target) => {
168
- if (target.locationId !== void 0) {
169
- session.move(character.id, {
170
- to: target.locationId,
171
- ignoreExits: true,
172
- ...target.position === void 0 ? {} : { position: target.position },
173
- ...target.featureKey === void 0 ? {} : { featureKey: target.featureKey }
174
- });
175
- moves.push({
176
- character: keyOfCharacter$1(character),
177
- name: character.name,
178
- to: session.locations.get(target.locationId)?.name ?? String(target.locationId),
179
- activity: target.activity
180
- });
181
- }
182
- if (session.characterStates.get(character.id)?.activity !== target.activity) session.characterStates.update(character.id, { activity: target.activity });
183
- };
184
- const alreadyAsked = new Set(Array.isArray(session.metadata.getValue(ASKED)) ? session.metadata.getValue(ASKED) : []);
185
- const asked = [];
186
- for (const character of session.characters.list()) {
187
- if (character.control === "player") continue;
188
- const characterId = character.id;
189
- const window = session.routines.list(characterId);
190
- const here = session.placements.get("character", characterId);
191
- const away = playerPlace === void 0 || here?.locationId !== playerPlace;
192
- if (window.length === 0) {
193
- if (ask && playerPlace !== void 0 && away && cursor !== void 0 && asked.length < MAX_ASKED && character.kind === "person" && character.tier !== "background" && !alreadyAsked.has(characterId)) {
194
- session.consolidation.enqueue({
195
- kind: "character",
196
- subjectId: characterId,
197
- note: "has no routine: give it a day (routines), as far as its role and the story imply",
198
- turn
199
- });
200
- asked.push(characterId);
201
- }
202
- continue;
203
- }
204
- if (!away) continue;
205
- const current = occurrenceAt(window, now, zone);
206
- const journey = journeys[characterId];
207
- if (journey !== void 0) {
208
- const same = current !== void 0 && current.window.id === journey.windowId && current.startsAt === journey.startsAt;
209
- if (same && now < journey.arriveAt) continue;
210
- delete journeys[characterId];
211
- if (same) {
212
- arrive(character, current.window);
213
- continue;
214
- }
215
- }
216
- if (current === void 0) continue;
217
- const before = cursor === void 0 ? void 0 : occurrenceAt(window, cursor, zone);
218
- if (before !== void 0 && before.window.id === current.window.id && before.startsAt === current.startsAt) continue;
219
- const target = current.window;
220
- if (target.locationId !== void 0 && (here?.locationId !== target.locationId || target.position !== void 0 && here.position !== target.position)) {
221
- const way = here?.locationId === target.locationId ? void 0 : session.planMove(characterId, { to: target.locationId });
222
- const seconds = way?.ok === true ? way.plan.travelSeconds : void 0;
223
- if (seconds !== void 0 && current.startsAt + seconds * 1e3 > now) {
224
- journeys[characterId] = {
225
- windowId: target.id,
226
- startsAt: current.startsAt,
227
- arriveAt: current.startsAt + seconds * 1e3
228
- };
229
- const text = `on the way to ${session.locations.get(target.locationId)?.name ?? String(target.locationId)}, for "${target.activity}"`;
230
- if (session.characterStates.get(characterId)?.activity !== text) session.characterStates.update(characterId, { activity: text });
231
- continue;
232
- }
233
- arrive(character, target);
234
- } else if (session.characterStates.get(characterId)?.activity !== target.activity) session.characterStates.update(characterId, { activity: target.activity });
235
- }
236
- session.metadata.setValue(CURSOR, now);
237
- session.metadata.setValue(TRAVEL, journeys);
238
- if (asked.length > 0) session.metadata.setValue(ASKED, [...alreadyAsked, ...asked]);
239
- return moves;
240
- });
241
- }
242
- /** A character's agenda at an instant, with places by name and others by name. */
243
- function agendaView(session, characterId, zone, now) {
244
- const agenda = agendaAt(session, characterId, now, zone, {
245
- horizon: NEXT_HORIZON,
246
- engagements: SHOWN_ENGAGEMENTS,
247
- goals: SHOWN_GOALS
248
- });
249
- const place = (id) => id === void 0 ? void 0 : session.locations.get(id)?.name;
250
- const names = (ids) => ids.filter((id) => id !== characterId).map((id) => session.characters.get(id)?.name ?? String(id));
251
- return {
252
- zone,
253
- ...agenda.now === void 0 ? {} : { now: {
254
- activity: agenda.now.window.activity,
255
- ...place(agenda.now.window.locationId) === void 0 ? {} : { place: place(agenda.now.window.locationId) },
256
- until: agenda.now.endsAt,
257
- interruptible: agenda.now.window.interruptible
258
- } },
259
- ...agenda.next === void 0 ? {} : { next: {
260
- activity: agenda.next.window.activity,
261
- ...place(agenda.next.window.locationId) === void 0 ? {} : { place: place(agenda.next.window.locationId) },
262
- at: agenda.next.startsAt
263
- } },
264
- engagements: agenda.engagements.map(({ engagement, overdue }) => ({
265
- title: engagement.title,
266
- at: engagement.at,
267
- ...place(engagement.locationId) === void 0 ? {} : { place: place(engagement.locationId) },
268
- with: names(engagement.participants),
269
- overdue
270
- })),
271
- goals: agenda.goals.map(({ intent, deadlineAt, overdue }) => ({
272
- name: intent.name,
273
- type: intent.type,
274
- description: intent.description,
275
- plan: intent.plan.slice(0, 3),
276
- ...deadlineAt === void 0 ? {} : { deadline: deadlineAt },
277
- overdue
278
- }))
279
- };
280
- }
281
- /** How soon ahead the game master is told of a window ending or a commitment falling due. */
282
- const SOON = 30 * MINUTE;
283
- const MAX_NOTES = 6;
284
- /** An engagement that has been overdue for longer than this is not worth the game master's attention every turn. */
285
- const STALE = 1440 * MINUTE;
286
- function sceneAgenda(session, zone, now, moved) {
287
- const player = session.characters.list().find((character) => character.control === "player");
288
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
289
- 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));
290
- const here = [];
291
- for (const characterId of withPlayer) {
292
- const windows = session.routines.list(characterId);
293
- const current = occurrenceAt(windows, now, zone);
294
- const upcoming = nextOccurrence(windows, now, zone, SOON);
295
- const name = session.characters.get(characterId)?.name ?? String(characterId);
296
- const place = current?.window.locationId === void 0 ? void 0 : session.locations.get(current.window.locationId);
297
- if (current !== void 0 && current.window.locationId !== void 0 && current.window.locationId !== playerPlace) here.push({
298
- name,
299
- note: `its day says "${current.window.activity}"${place === void 0 ? "" : ` at ${place.name}`} now, yet it is here`
300
- });
301
- else if (current !== void 0 && current.endsAt - now <= SOON) here.push({
302
- name,
303
- note: `"${current.window.activity}" is due to end soon`
304
- });
305
- else if (current === void 0 && upcoming !== void 0) here.push({
306
- name,
307
- note: `"${upcoming.window.activity}" begins soon${upcoming.window.locationId === void 0 ? "" : ` at ${session.locations.get(upcoming.window.locationId)?.name ?? ""}`}`
308
- });
309
- }
310
- const engagements = session.engagements.list({
311
- status: "pending",
312
- to: now + SOON
313
- }).filter((engagement) => now - (engagement.until ?? engagement.at) < STALE).slice(0, MAX_NOTES).map((engagement) => ({
314
- title: engagement.title,
315
- at: engagement.at,
316
- ...engagement.locationId === void 0 ? {} : { place: session.locations.get(engagement.locationId)?.name ?? "" },
317
- with: engagement.participants.map((id) => session.characters.get(id)?.name ?? String(id)),
318
- overdue: now > (engagement.until ?? engagement.at + ENGAGEMENT_GRACE)
319
- }));
320
- return {
321
- zone,
322
- moved,
323
- here: here.slice(0, MAX_NOTES),
324
- engagements
325
- };
326
- }
327
- //#endregion
328
- //#region src/host/clock/passage.ts
329
- /** The start of a turn: the time, how long the player was away, and what the days of the characters make of it. */
330
- function startTurn(session, config, turn, wall) {
331
- const started = beginTurn(session, config, turn, wall);
332
- const moved = catchUpRoutines(session, started.time.zone, started.time.now, turn, true);
333
- return {
334
- ...started,
335
- agenda: sceneAgenda(session, started.time.zone, started.time.now, moved)
336
- };
337
- }
338
- /** A round passes, and the characters outside the scene take up what their days have for the new time. */
339
- function passRound(session, config, turn, round, wall, stated, minimum) {
340
- const span = endRound(session, config, turn, round, wall, stated, minimum);
341
- return {
342
- ...span,
343
- moved: catchUpRoutines(session, span.zone, span.to, turn, false)
344
- };
345
- }
346
- /** Time is skipped, and the characters outside the scene take up what their days have for the new time. */
347
- function skipAhead(session, config, turn, round, wall, request) {
348
- const span = skipTime(session, config, turn, round, wall, request);
349
- return {
350
- ...span,
351
- moved: catchUpRoutines(session, span.zone, span.to, turn, true)
352
- };
353
- }
354
- /** What a character is told of its own agenda. */
355
- function agendaFor(session, config, turn, wall, characterId) {
356
- const time = readTime(session, config, turn, wall());
357
- return agendaView(session, characterId, zoneOf(config), time.now);
358
- }
359
- //#endregion
360
- //#region src/host/clock/offscene.ts
361
- const HANDLED = "offscene.handled";
362
- const keyOf = (character) => character.sourceId ?? String(character.id);
363
- function handledKeys(session) {
364
- const stored = session.metadata.getValue(HANDLED);
365
- return new Set(Array.isArray(stored) ? stored.filter((entry) => typeof entry === "string") : []);
366
- }
367
- /** Remember that these were dealt with, so that they are not dealt with again. */
368
- function markHandled(session, keys) {
369
- session.metadata.setValue(HANDLED, [...handledKeys(session), ...keys].slice(-500));
370
- }
371
- /**
372
- * What has fallen due for characters who are not with the player and who have not dealt with it yet: commitments
373
- * whose time has come with everyone to do with them away from the scene, and goals whose deadline has passed.
374
- * Oldest first.
375
- */
376
- function dueOffScene(session, zone, now, language = "en") {
377
- const tr = translator(language);
378
- const when = (instant) => describeWhen(instant, now, zone, language);
379
- const handled = handledKeys(session);
380
- const characters = session.characters.list();
381
- const player = characters.find((character) => character.control === "player");
382
- const playerPlace = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
383
- const away = (id) => playerPlace !== void 0 && session.placements.get("character", id)?.locationId !== playerPlace;
384
- const agents = new Map(characters.filter((character) => character.control === "agent").map((character) => [character.id, character]));
385
- const items = [];
386
- for (const engagement of session.engagements.list({
387
- status: "pending",
388
- to: now + 1
389
- })) {
390
- const key = `e${engagement.id}`;
391
- if (handled.has(key) || now < engagement.at + 1) continue;
392
- const everyone = engagement.participants;
393
- if (everyone.some((id) => !agents.has(id) || !away(id))) continue;
394
- const place = engagement.locationId === void 0 ? void 0 : session.locations.get(engagement.locationId);
395
- items.push({
396
- key,
397
- kind: "engagement",
398
- at: engagement.at,
399
- characters: everyone.map((id) => keyOf(agents.get(id))),
400
- ...place === void 0 ? {} : { place: place.sourceId ?? String(place.id) },
401
- text: [
402
- `${place === void 0 ? tr("You were to {title}, at {when}", {
403
- title: engagement.title,
404
- when: when(engagement.at)
405
- }) : tr("You were to {title} at {place}, at {when}", {
406
- title: engagement.title,
407
- place: place.name,
408
- when: when(engagement.at)
409
- })}${engagement.note === "" ? "" : tr(" ({note})", { note: engagement.note })}${tr(".")}`,
410
- 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) }),
411
- tr("It was with: {who}.", { who: everyone.map((id) => agents.get(id).name).join(tr(", ")) }),
412
- tr("You are not with the player's character, and nothing of this happens in front of anyone: decide what you do about it.")
413
- ].join(" ")
414
- });
415
- }
416
- for (const character of agents.values()) {
417
- if (!away(character.id)) continue;
418
- for (const goal of session.intents.list(character.id, { status: "active" })) {
419
- const key = `g${goal.id}`;
420
- let deadline;
421
- try {
422
- deadline = goal.deadline === void 0 ? void 0 : parseInstant(goal.deadline, zone);
423
- } catch {
424
- deadline = void 0;
425
- }
426
- if (handled.has(key) || deadline === void 0 || deadline >= now) continue;
427
- items.push({
428
- key,
429
- kind: "goal",
430
- at: deadline,
431
- characters: [keyOf(character)],
432
- text: `${tr("The time you had for \"{goal}\" has passed ({when}; it is {now} now)", {
433
- goal: goal.name,
434
- when: when(deadline),
435
- now: when(now)
436
- })}${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.")}`
437
- });
438
- }
439
- }
440
- return items.sort((a, b) => a.at - b.at);
441
- }
442
- //#endregion
443
- //#region src/host/variables/describe.ts
444
- /** What is tracked of a subject, in a line: `Health: hurt (2); Valence: unhappy (-0.4), usually even (0)`. */
445
- function describeShown(shown) {
446
- return shown.map(({ variable, value, baseline }) => {
447
- const usual = baseline !== void 0 && baseline !== value ? `, usually ${describeValue(variable, baseline)}` : "";
448
- return `${variable.name}: ${describeValue(variable, value)}${usual}`;
449
- }).join("; ");
450
- }
451
- //#endregion
452
- //#region src/host/orchestration/store.ts
453
- /** The rules the session copied from its world when it started. */
454
- function worldRules(session) {
455
- const value = session.metadata.getValue(WORLD_RULES_KEY);
456
- return Array.isArray(value) ? value.filter((rule) => typeof rule === "string") : [];
457
- }
458
- const keyOfCharacter = (character) => character.sourceId ?? String(character.id);
459
- function placeOf(session, characterId) {
460
- const placement = session.placements.get("character", characterId);
461
- const location = placement === void 0 ? void 0 : session.locations.get(placement.locationId);
462
- if (placement === void 0 || location === void 0) return void 0;
463
- const feature = placement.featureKey === void 0 ? void 0 : location.features.find((candidate) => candidate.key === placement.featureKey);
464
- return {
465
- location,
466
- position: placement.position,
467
- ...feature === void 0 ? {} : { feature }
468
- };
469
- }
470
- function castOf(session) {
471
- return session.characters.list().map((character) => {
472
- const state = session.characterStates.get(character.id);
473
- const place = placeOf(session, character.id);
474
- return {
475
- key: keyOfCharacter(character),
476
- character,
477
- ...state === void 0 ? {} : { state },
478
- ...place === void 0 ? {} : { place }
479
- };
480
- });
481
- }
482
- /** How much of what is in a container is told: a bag with fifty things in it is not recited. */
483
- const SHOWN_CONTENTS = 5;
484
- function viewOf(session, id, where) {
485
- const item = session.items.get(id);
486
- if (item === void 0) return void 0;
487
- const inside = item.container?.state === "open" ? session.items.contents({
488
- kind: "item",
489
- id
490
- }).filter((entry) => !entry.item.hidden).map((entry) => entry.item.quantity > 1 ? `${entry.item.quantity} ${entry.item.name}` : entry.item.name) : void 0;
491
- return {
492
- key: itemKey(item),
493
- name: item.name,
494
- quantity: item.quantity,
495
- quality: item.quality,
496
- notable: item.notable,
497
- hidden: item.hidden,
498
- ...item.container === void 0 ? {} : { state: item.container.state },
499
- ...inside === void 0 || inside.length === 0 ? {} : { contents: [...inside.slice(0, SHOWN_CONTENTS), ...inside.length > SHOWN_CONTENTS ? [`and ${inside.length - SHOWN_CONTENTS} more`] : []] },
500
- ...where === void 0 || where === "" ? {} : { where }
501
- };
502
- }
503
- /** What lies in a place, notable things first; hidden things are included only when asked for. */
504
- function itemsIn(session, locationId, withHidden) {
505
- return session.items.contents({
506
- kind: "location",
507
- id: locationId
508
- }).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) => {
509
- const holder = entry.holding.holder;
510
- const feature = holder.kind === "location" && holder.featureKey !== void 0 ? session.locations.get(locationId)?.features.find((candidate) => candidate.key === holder.featureKey)?.name : void 0;
511
- const where = holder.kind === "location" ? [holder.position, feature === void 0 ? void 0 : `at ${feature}`].filter((part) => part !== void 0 && part !== "").join(", ") : "";
512
- const view = viewOf(session, entry.item.id, where);
513
- return view === void 0 ? [] : [view];
514
- });
515
- }
516
- function carriedBy(session, characterId) {
517
- return session.items.contents({
518
- kind: "character",
519
- id: characterId
520
- }).sort((a, b) => Number(b.item.notable) - Number(a.item.notable) || a.item.id - b.item.id).flatMap((entry) => {
521
- const holder = entry.holding.holder;
522
- const view = viewOf(session, entry.item.id, holder.kind === "character" && holder.mode === "worn" ? `worn on the ${holder.slot}` : "carried");
523
- return view === void 0 ? [] : [view];
524
- });
525
- }
526
- function knowledgeOf(session, characterId, turn, visibleCharacters) {
527
- observeSurroundings(session, characterId, turn);
528
- const placement = session.placements.get("character", characterId);
529
- 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);
530
- const locations = session.knowledge.list(characterId, "location").flatMap((entry) => {
531
- const place = session.locations.get(entry.subjectId);
532
- return place === void 0 ? [] : [place.name];
533
- });
534
- const items = session.knowledge.list(characterId, "item").flatMap((entry) => {
535
- const item = session.items.get(entry.subjectId);
536
- return item === void 0 ? [] : [item.name];
537
- });
538
- const allExits = session.locations.allExits();
539
- const routes = session.knowledge.list(characterId, "exit").flatMap((entry) => {
540
- const exit = allExits.find((candidate) => candidate.id === entry.subjectId);
541
- const from = exit === void 0 ? void 0 : session.locations.get(exit.fromId);
542
- const to = exit === void 0 ? void 0 : session.locations.get(exit.toId);
543
- return from === void 0 || to === void 0 ? [] : [`${from.name} -> ${to.name}`];
544
- });
545
- return {
546
- characters: session.relationships.from(characterId).flatMap((relation) => {
547
- const character = session.characters.get(relation.toId);
548
- return character === void 0 ? [] : [character.name];
549
- }),
550
- factions: session.factionRelationships.from("character", characterId).filter((relation) => relation.toKind === "faction").flatMap((relation) => {
551
- const faction = session.factions.get(relation.toId);
552
- return faction === void 0 ? [] : [faction.name];
553
- }),
554
- locations,
555
- items,
556
- routes
557
- };
558
- }
559
- function affiliationsOf(session, characterId) {
560
- return session.factionMemberships.ofCharacter(characterId).flatMap((membership) => {
561
- const faction = session.factions.get(membership.factionId);
562
- if (faction === void 0) return [];
563
- const relation = session.factionRelationships.get("character", characterId, "faction", faction.id);
564
- const relationship = relation === void 0 ? void 0 : {
565
- name: faction.name,
566
- label: relation.label,
567
- summary: relation.summary,
568
- present: false,
569
- familiarity: relation.familiarity,
570
- trust: relation.trust,
571
- affinity: relation.affinity,
572
- tension: relation.tension
573
- };
574
- return [{
575
- name: faction.name,
576
- role: membership.role,
577
- rank: membership.rank,
578
- status: membership.status,
579
- commitment: membership.commitment,
580
- publicState: session.factionStates.get(faction.id)?.publicState ?? "",
581
- goals: session.factionIntents.list(faction.id, { status: "active" }).map((intent) => intent.name),
582
- ...relationship === void 0 ? {} : { relationship }
583
- }];
584
- });
585
- }
586
- function placeViewOf(session, locationId) {
587
- const location = session.locations.get(locationId);
588
- if (location === void 0) return void 0;
589
- const here = new Set(session.placements.at(locationId, "character").map((placement) => placement.entityId));
590
- return {
591
- key: locationKey(location),
592
- location,
593
- exits: session.locations.exitsFrom(locationId).flatMap((exit) => {
594
- const to = session.locations.get(exit.toId);
595
- return to === void 0 ? [] : [{
596
- key: locationKey(to),
597
- name: to.name,
598
- exit
599
- }];
600
- }),
601
- here: castOf(session).filter((member) => here.has(member.character.id)),
602
- items: itemsIn(session, locationId, false)
603
- };
604
- }
605
- var DryRunDone = class extends Error {};
606
- /** Do the changes in order inside a transaction that is always undone, so that a later change sees the earlier ones. */
607
- function dryRunItems(session, entries) {
608
- const problems = [];
609
- const effects = [];
610
- try {
611
- session.transaction(() => {
612
- for (const entry of entries) {
613
- const character = session.characters.list().find((candidate) => keyOfCharacter(candidate) === entry.character);
614
- const mine = [];
615
- effects.push(mine);
616
- if (character === void 0) {
617
- problems.push(`${entry.character}: there is no such character`);
618
- continue;
619
- }
620
- for (const spec of entry.changes) {
621
- const planned = planItemChange(session, character.id, spec);
622
- if (!planned.ok) {
623
- problems.push(...planned.problems.map((problem) => `${entry.character}: cannot ${spec.action} ${spec.item}: ${problem}`));
624
- break;
625
- }
626
- mine.push(applyItemPlan(session, planned.plan));
627
- }
628
- }
629
- throw new DryRunDone();
630
- });
631
- } catch (error) {
632
- if (!(error instanceof DryRunDone)) throw error;
633
- }
634
- return problems.length === 0 ? {
635
- ok: true,
636
- effects
637
- } : {
638
- ok: false,
639
- problems
640
- };
641
- }
642
- /** What a character can tell of itself and of those with it, in words. */
643
- function trackedFor(session, characterId, presentIds) {
644
- const character = session.characters.get(characterId);
645
- return {
646
- self: character === void 0 ? "" : describeShown(shownVariables(session, "character", characterId, keyOfCharacter(character), "self")),
647
- others: presentIds.filter((id) => id !== characterId).flatMap((id) => {
648
- const other = session.characters.get(id);
649
- const text = other === void 0 ? "" : describeShown(shownVariables(session, "character", id, keyOfCharacter(other), "others"));
650
- return other === void 0 || text === "" ? [] : [{
651
- name: other.name,
652
- text
653
- }];
654
- })
655
- };
656
- }
657
- /** At most this many lines of what the story tracks are told to the game master at once. */
658
- const MAX_TRACKED_LINES = 14;
659
- /** What the story tracks, for the game master: everything, the scene first. */
660
- function trackedLines(session) {
661
- const player = session.characters.list().find((character) => character.control === "player");
662
- const here = player === void 0 ? void 0 : session.placements.get("character", player.id)?.locationId;
663
- const near = (characterId) => here !== void 0 && session.placements.get("character", characterId)?.locationId === here ? 0 : 1;
664
- const lines = [];
665
- const world = describeShown(shownVariables(session, "world", 0, "world", "story"));
666
- if (world !== "") lines.push(`the world: ${world}`);
667
- if (here !== void 0) {
668
- const place = session.locations.get(here);
669
- const text = place === void 0 ? "" : describeShown(shownVariables(session, "location", here, locationKey(place), "story"));
670
- if (place !== void 0 && text !== "") lines.push(`${place.name} (${locationKey(place)}): ${text}`);
671
- for (const entry of session.items.contents({
672
- kind: "location",
673
- id: here
674
- })) {
675
- const text = describeShown(shownVariables(session, "item", entry.item.id, itemKey(entry.item), "story"));
676
- if (text !== "") lines.push(`${entry.item.name} (${itemKey(entry.item)}): ${text}`);
677
- }
678
- }
679
- for (const character of [...session.characters.list()].sort((a, b) => near(a.id) - near(b.id))) {
680
- const text = describeShown(shownVariables(session, "character", character.id, keyOfCharacter(character), "story"));
681
- if (text !== "") lines.push(`${character.name} (${keyOfCharacter(character)}): ${text}`);
682
- }
683
- return lines.slice(0, MAX_TRACKED_LINES);
684
- }
685
- function checkMove(session, characterKey, request) {
686
- const character = session.characters.list().find((candidate) => keyOfCharacter(candidate) === characterKey);
687
- if (character === void 0) return {
688
- ok: false,
689
- problems: [`there is no character "${characterKey}"`]
690
- };
691
- const to = session.locations.list().find((candidate) => locationKey(candidate) === request.location);
692
- if (to === void 0) return {
693
- ok: false,
694
- problems: [`there is no place "${request.location}" (list_locations shows the keys)`]
695
- };
696
- const move = {
697
- to: to.id,
698
- ...request.position === void 0 ? {} : { position: request.position },
699
- ...request.feature === void 0 ? {} : { featureKey: request.feature },
700
- ...request.ignoreExits === true ? { ignoreExits: true } : {}
701
- };
702
- const planned = session.planKnownMove(character.id, move);
703
- return planned.ok ? {
704
- ok: true,
705
- move,
706
- plan: planned.plan,
707
- to: {
708
- key: locationKey(to),
709
- name: to.name
710
- },
711
- ...request.position === void 0 ? {} : { position: request.position }
712
- } : {
713
- ok: false,
714
- problems: planned.problems
715
- };
716
- }
717
- function storeOf(session, folder, problem, queryVector, wall, prompt) {
718
- const settings = () => liveSettings(folder, problem);
719
- return {
720
- story: session,
721
- cast: () => castOf(session),
722
- checkMove: (character, request) => checkMove(session, character, request),
723
- place: (locationId) => placeViewOf(session, locationId),
724
- settings,
725
- text: (id, variables) => prompt(settings().prompts.language, id, variables),
726
- rules: () => rulesOf(worldRules(session), settings().rules.own),
727
- time: (turn) => readTime(session, settings().clock, turn, wall()),
728
- beginTurn: (turn) => {
729
- observeAsPlayer(session, turn);
730
- return startTurn(session, settings().clock, turn, wall());
731
- },
732
- endRound: (turn, round, stated, minimum) => passRound(session, settings().clock, turn, round, wall(), stated, minimum),
733
- skipTime: (turn, round, request) => skipAhead(session, settings().clock, turn, round, wall(), request),
734
- checkVariableChanges: (changes) => changes.flatMap((spec) => {
735
- const planned = planVariableChange(session, spec);
736
- return planned.ok ? [] : planned.problems;
737
- }),
738
- changeVariables: (turn, changes) => session.transaction(() => changes.map((spec) => changeVariable(session, spec, turn))),
739
- trackedFor: (characterId, presentIds) => trackedFor(session, characterId, presentIds),
740
- tracked: () => trackedLines(session),
741
- dueOffScene: (turn) => dueOffScene(session, zoneOf(settings().clock), readTime(session, settings().clock, turn, wall()).now, languageOf(settings().prompts.language)),
742
- markHandled: (keys) => {
743
- markHandled(session, keys);
744
- },
745
- runTriggers: (turn, round) => {
746
- const settings = liveSettings(folder, problem);
747
- const { now, zone } = readTime(session, settings.clock, turn, wall());
748
- return fireTriggers(session, {
749
- settings,
750
- turn,
751
- round,
752
- now,
753
- zone,
754
- problem
755
- });
756
- },
757
- ...noteStore(session, () => liveSettings(folder, problem), (turn) => {
758
- const { now, zone } = readTime(session, liveSettings(folder, problem).clock, turn, wall());
759
- return {
760
- now,
761
- zone
762
- };
763
- }),
764
- putNote: (note) => {
765
- putNote(session, note);
766
- },
767
- addNote: (kind, turn, lines) => {
768
- addToNote(session, kind, turn, lines);
769
- },
770
- recordActivity: (entry, detail) => {
771
- if (detail !== void 0 && entry.run !== void 0) keepRunDetail(folder, entry.run, detail);
772
- forgetRunDetails(folder, recordActivity(session, entry));
773
- if (entry.turn !== void 0 && entry.tokens !== void 0) addUsage(session, entry.turn, "helper", entry.tokens);
774
- },
775
- recordUsage: (turn, tokens) => {
776
- addUsage(session, turn, "master", tokens);
777
- },
778
- notes: () => readNotes(session),
779
- clearNotes: () => {
780
- clearNotes(session);
781
- },
782
- agenda: (turn, characterId) => agendaFor(session, settings().clock, turn, wall, characterId),
783
- commit: (updates) => session.transaction(() => updates.map(({ character, patch, move, items }) => {
784
- session.characterStates.update(character, patch);
785
- const effects = (items ?? []).map((spec) => changeItem(session, character, spec));
786
- if (move !== void 0) session.move(character, move);
787
- return effects;
788
- })),
789
- checkItemChanges: (entries) => dryRunItems(session, entries),
790
- carried: (characterId) => carriedBy(session, characterId),
791
- knowledge: (characterId, turn, visibleCharacters) => knowledgeOf(session, characterId, turn, visibleCharacters),
792
- affiliations: (characterId) => affiliationsOf(session, characterId),
793
- itemsAt: (locationId, withHidden = false) => itemsIn(session, locationId, withHidden),
794
- completeTurn: () => {
795
- session.metadata.recordTurn();
796
- },
797
- queueCommit: (record) => {
798
- session.pendingCommits.enqueue(record.turn, record.round, JSON.parse(JSON.stringify(record)));
799
- },
800
- pendingCommits: () => session.pendingCommits.list().map((entry) => entry.payload),
801
- completeCommits: (rounds) => {
802
- session.transaction(() => {
803
- session.events.seal();
804
- session.pendingCommits.complete(rounds);
805
- });
806
- },
807
- queryVector
808
- };
809
- }
810
- /** Opens the store of the roleplay session behind a chat; a chat that is not one gets none. */
811
- function storesOf(state, sessionsDir, problem = () => void 0, queryVector = () => Promise.resolve(void 0), wall = Date.now, prompt = (language, id, variables) => shippedText(id, language, variables)) {
812
- return (chat) => {
813
- const id = roleplaySessionOf(chat);
814
- if (id === void 0) return void 0;
815
- try {
816
- 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));
817
- } catch {
818
- return;
819
- }
820
- };
821
- }
822
- //#endregion
823
- //#region src/shared/roll.ts
824
- /** The player rolls dice before acting: `/roll 2d6+1 pick the lock`. The dice are then part of what the game master judges. */
825
- const ROLL_COMMAND = /^\s*\/roll(?=\s|$)\s*(\S*)\s*([\s\S]*)$/i;
826
- /** 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. */
827
- function parseRoll(text) {
828
- const match = ROLL_COMMAND.exec(text);
829
- return match === null ? void 0 : {
830
- expression: match[1] ?? "",
831
- reason: (match[2] ?? "").trim()
832
- };
833
- }
834
- //#endregion
835
- //#region src/host/orchestration/hooks.ts
836
- const notice = (text) => createUserMessage({
837
- content: [{
838
- type: "text",
839
- text
840
- }],
841
- source: { kind: "roleplay" }
842
- });
843
- /** The turn of the game master of a roleplay chat; characters and other chats have none. */
844
- function ownerOf(agent, turn) {
845
- if (agent.session.header.origin === "subagent") return void 0;
846
- return roleplaySessionOf(agent.session.id) === void 0 ? void 0 : {
847
- chat: agent.session.id,
848
- turn
849
- };
850
- }
851
- /** 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. */
852
- const PREVIEW_SHOWN = Symbol.for("dsh-agentic-roleplay.preview-tool");
853
- /** Registers the preview tool on the agent of a chat that shows one, once, and withdraws it when the setting is turned off. */
854
- function previewToggle(tool) {
855
- return (agent, enabled) => {
856
- const holder = agent;
857
- const withdraw = holder[PREVIEW_SHOWN];
858
- if (enabled && withdraw === void 0) try {
859
- holder[PREVIEW_SHOWN] = agent.ctx.tools.register(tool);
860
- } catch (error) {
861
- if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
862
- holder[PREVIEW_SHOWN] = () => void 0;
863
- }
864
- else if (!enabled && withdraw !== void 0) {
865
- delete holder[PREVIEW_SHOWN];
866
- withdraw();
867
- }
868
- };
869
- }
870
- /** 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. */
871
- const OPTIONAL_SHOWN = Symbol.for("dsh-agentic-roleplay.optional-tools");
872
- /** 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. */
873
- function optionalToolSwitch(tools) {
874
- return (agent, enabled) => {
875
- const holder = agent;
876
- const shown = holder[OPTIONAL_SHOWN] ??= /* @__PURE__ */ new Map();
877
- for (const tool of tools) {
878
- const withdraw = shown.get(tool.name);
879
- if (enabled(tool.name) && withdraw === void 0) try {
880
- shown.set(tool.name, agent.ctx.tools.register(tool));
881
- } catch (error) {
882
- if (!(error instanceof Error) || !error.message.includes("already registered")) throw error;
883
- shown.set(tool.name, () => void 0);
884
- }
885
- else if (!enabled(tool.name) && withdraw !== void 0) {
886
- shown.delete(tool.name);
887
- withdraw();
888
- }
889
- }
890
- };
891
- }
892
- /** 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. */
893
- const EXTERNAL_LIMIT = Symbol.for("dsh-agentic-roleplay.external-limit");
894
- /**
895
- * 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
896
- * 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.
897
- */
898
- function externalToolLimit(agent, withheld) {
899
- const holder = agent;
900
- const key = [...withheld].sort().join("\n");
901
- const current = holder[EXTERNAL_LIMIT];
902
- if (current?.key === key) return;
903
- current?.lift();
904
- delete holder[EXTERNAL_LIMIT];
905
- if (withheld.length > 0) holder[EXTERNAL_LIMIT] = {
906
- key,
907
- lift: agent.ctx.tools.restrict({ deny: [...withheld] })
908
- };
909
- }
910
- /**
911
- * The listeners of a roleplay preset. Preset listeners are shared by every chat
912
- * that uses the preset and also hear the agents that chat spawns, so each one
913
- * first checks that it is looking at the game master of a roleplay chat.
914
- */
915
- function installHooks(ctx, deps) {
916
- const { engine, boundaries, stores, timelines, previewTool } = deps;
917
- const showPreviewTool = previewToggle(previewTool);
918
- const showOptionalTools = optionalToolSwitch(deps.optionalTools ?? []);
919
- /** 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. */
920
- const applyTools = (agent, store) => {
921
- const { tools } = store.settings();
922
- showOptionalTools(agent, (tool) => toolEnabled(tools, "gameMaster", tool));
923
- externalToolLimit(agent, externalWithheld(agent.ctx.tools, tools, "gameMaster"));
924
- };
925
- ctx.on("agent/created", ({ agent }) => {
926
- const owner = ownerOf(agent, 0);
927
- const store = owner === void 0 ? void 0 : stores(owner.chat);
928
- if (store !== void 0) applyTools(agent, store);
929
- });
930
- ctx.on("session/event", (session, event) => {
931
- if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
932
- timelines.ended(session.id, session, event.seq);
933
- const events = session.snapshotEvents();
934
- const began = events.findLastIndex((entry) => entry.type === "turn/start");
935
- const start = began === -1 ? void 0 : events[began];
936
- if (start?.type === "turn/start") stores(session.id)?.recordUsage?.(start.data.turn, tokensOf(events.slice(began)));
937
- });
938
- ctx.on("agent/created", async ({ agent }) => {
939
- const { header } = agent.session;
940
- if (header.origin === "subagent" || !header.isSeeded || header.parentSession === void 0) return;
941
- if (roleplaySessionOf(agent.session.id) === void 0 || roleplaySessionOf(header.parentSession) === void 0) return;
942
- await timelines.adopt(agent.session.id, header.parentSession, agent.session.inheritedEventCount - 1, agent);
943
- });
944
- ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
945
- const owner = ownerOf(agent, turn);
946
- if (owner === void 0) return;
947
- const missing = engine.missing(owner);
948
- if (missing === void 0) return;
949
- if (!engine.object(owner)) {
950
- ctx.logger.warn(`roleplay: ${owner.chat} ended turn ${turn} without finishing it (${missing})`);
951
- return;
952
- }
953
- agent.steer(notice(`You may not end the turn yet: ${missing}.`));
954
- });
955
- ctx.on("agent/pre-step", async (payload, next) => {
956
- const decision = await next();
957
- const owner = ownerOf(payload.agent, payload.turn);
958
- const store = owner === void 0 ? void 0 : stores(owner.chat);
959
- if (owner !== void 0 && store !== void 0) {
960
- showPreviewTool(payload.agent, store.settings().preview.enabled);
961
- applyTools(payload.agent, store);
962
- }
963
- if (decision.kind !== "enter" || payload.step !== 1) return decision;
964
- if (owner === void 0 || store === void 0) return decision;
965
- const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
966
- await timelines.begin(owner.chat, payload.turn, text);
967
- const cast = store.cast();
968
- const ooc = parseOoc(text);
969
- const verdict = ooc === void 0 ? boundaries().inputValidator.validate({
970
- text,
971
- turn: payload.turn,
972
- cast
973
- }) : { ok: true };
974
- if (ooc !== void 0 && ooc.request !== "") engine.beginOoc(owner, ooc.request, ooc.question);
975
- else if (ooc === void 0) engine.expectJudgement(owner);
976
- const queryVector = await store.queryVector(ooc?.request ?? text);
977
- store.clearNotes();
978
- store.lapseNotes(payload.turn);
979
- const { time, away, agenda } = store.beginTurn(payload.turn);
980
- const tr = translator(languageOf(store.settings().prompts.language));
981
- if (store.settings().offstage.summary) store.addNote("away", payload.turn, agenda.moved.map((move) => tr("{name} went to {place}.", {
982
- name: move.name,
983
- place: move.to
984
- })));
985
- const world = {
986
- happened: engine.fireAtStart(owner).flatMap((entry) => [...entry.events.map((text) => `${entry.name}: ${text}`), ...entry.cues.map((cue) => tr("{names} noticed: {text}", {
987
- names: cue.names.join(tr(" and ")),
988
- text: cue.text
989
- }))]),
990
- beats: store.pendingBeats(),
991
- upcoming: store.upcoming(payload.turn)
992
- };
993
- const tracked = store.tracked();
994
- const lines = [boundaries().sceneContext.scene({
995
- ...tracked.length === 0 ? {} : { tracked },
996
- time: {
997
- now: time,
998
- agenda,
999
- ...away === void 0 ? {} : { away }
1000
- },
1001
- ...world.happened.length === 0 && world.beats.length === 0 && world.upcoming.length === 0 ? {} : { world },
1002
- cast,
1003
- turn: payload.turn,
1004
- input: text,
1005
- story: store.story,
1006
- items: {
1007
- at: (locationId) => store.itemsAt(locationId, true),
1008
- carried: (characterId) => store.carried(characterId)
1009
- },
1010
- language: store.settings().prompts.language,
1011
- ...queryVector === void 0 ? {} : { queryVector }
1012
- })];
1013
- const pacing = ooc === void 0 ? pacingAdvice(store, payload.turn) : void 0;
1014
- if (pacing !== void 0) lines.push(describePacingAdvice(pacing));
1015
- else if (ooc === void 0 && plotAuthorNeeded(store, payload.turn)) lines.push(store.text("roleplay/plot-hint"));
1016
- const rules = store.rules();
1017
- if (rules.length > 0) lines.push(store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
1018
- const wanted = ooc === void 0 ? parseRoll(text) : void 0;
1019
- if (wanted !== void 0) try {
1020
- const made = rollPlain(wanted.expression);
1021
- const roll = store.story.dice.record({
1022
- turn: payload.turn,
1023
- expression: made.expression,
1024
- faces: made.faces,
1025
- kept: made.kept,
1026
- modifier: made.modifier,
1027
- total: made.total,
1028
- value: made.total,
1029
- reason: wanted.reason === "" ? tr("the player's roll") : wanted.reason,
1030
- by: "player"
1031
- });
1032
- 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.", {
1033
- dice: roll.expression,
1034
- reason: roll.reason,
1035
- total: roll.total,
1036
- faces: `[${roll.faces.join(", ")}]`
1037
- }));
1038
- } catch (error) {
1039
- engine.skip(owner);
1040
- lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
1041
- }
1042
- if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
1043
- if (ooc !== void 0 && ooc.request === "") {
1044
- engine.skip(owner);
1045
- lines.push(store.text("roleplay/ooc-empty", { command: ooc.question ? "/ask" : "/ooc" }));
1046
- }
1047
- if (!verdict.ok) {
1048
- engine.skip(owner);
1049
- lines.push(store.text("roleplay/input-refused", { reason: verdict.reason }));
1050
- }
1051
- return {
1052
- ...decision,
1053
- messages: [...decision.messages, notice(lines.join("\n\n"))]
1054
- };
1055
- });
1056
- }
1057
- //#endregion
1058
- export { writeVerdicts as a, readVerdicts as i, installHooks as n, storesOf as r, externalToolLimit as t };
1059
-
1060
- //# sourceMappingURL=hooks-DdO_tNhu.js.map