@dsh-agentic-roleplay/core 0.10.0 → 0.10.2

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 (37) hide show
  1. package/README.md +1 -1
  2. package/icon.svg +13 -0
  3. package/lib/{authoring-tools-B4mEdKp_.js → authoring-tools-C9cmcUbD.js} +1820 -1243
  4. package/lib/authoring.js +18 -7
  5. package/lib/{child-Dtv76jNx.js → child-C9nPIy9j.js} +40 -5
  6. package/lib/client.js +4668 -2249
  7. package/lib/client.js.map +1 -1
  8. package/lib/compaction.js +2 -2
  9. package/lib/doctor.js +3 -3
  10. package/lib/{gallery-BZJleAeH.js → gallery-CtG-bDzz.js} +2 -2
  11. package/lib/{generator-Cg6CQc5S.js → generator-nLoPM5MF.js} +2 -2
  12. package/lib/helper.js +8 -1
  13. package/lib/{hooks-DTjHWTfx.js → hooks-BpLN_hhT.js} +282 -211
  14. package/lib/images.js +4 -4
  15. package/lib/index.js +1399 -146
  16. package/lib/{library-GIlrkOim.js → library-CH-ahlm0.js} +2 -2
  17. package/lib/{lorebook-author-tools-BCFFJSle.js → lorebook-author-tools-Cg7QQemi.js} +6 -6
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-BVzew4-K.js → narration-B0hConSw.js} +5 -2
  20. package/lib/orchestration.js +108 -21
  21. package/lib/{pack-jail-hsNQNTOf.js → pack-jail-D5j5mIq6.js} +16 -12
  22. package/lib/{packs-UpK_cvI4.js → packs-Cc05FrId.js} +2 -2
  23. package/lib/{presenter-agent-DZOgBOR9.js → presenter-agent-UKbKYXMO.js} +6 -6
  24. package/lib/{preset-Cyoj1ZWa.js → preset-Be4lz6vB.js} +4 -4
  25. package/lib/{preset-author-tools-RSta6pHK.js → preset-author-tools-C3s0iSfv.js} +6 -6
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-CvpsW_10.js → presets-Cl9sU3Qs.js} +152 -14
  28. package/lib/{reflection-0qTvw2It.js → reflection-I9z-PvFK.js} +135 -93
  29. package/lib/{text-CbGQhK1-.js → text-CzqhC8sT.js} +11 -1
  30. package/lib/{turn-guard-BzNeGNnc.js → turn-guard-B9pGCeir.js} +3 -3
  31. package/package.json +4 -2
  32. package/prompts/en/checks/decide-opening.md +7 -1
  33. package/prompts/en/checks/decide-stated.md +1 -0
  34. package/prompts/en/roleplay/record-keeper.md +2 -1
  35. package/prompts/zh/checks/decide-opening.md +7 -1
  36. package/prompts/zh/checks/decide-stated.md +1 -0
  37. package/prompts/zh/roleplay/record-keeper.md +2 -1
@@ -1,15 +1,15 @@
1
1
  import { l as roleplaySessionOf, t as promptFor } from "./access-CXtaZNbx.js";
2
- import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-BVzew4-K.js";
3
- import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CbGQhK1-.js";
4
- import { _ as addTokens, a as childTrace, c as runChild, f as requestsOf, g as NO_TOKENS, h as tokensOf, m as estimateTokens, n as childModel, p as blockText, r as childSampling, x as estimateAnswer } from "./child-Dtv76jNx.js";
2
+ import { _ as emptyStats, a as liveSettings, h as DECISION_SITES, m as rulesOf, n as encodeOutput, p as WORLD_RULES_KEY, r as encodePreview } from "./narration-B0hConSw.js";
3
+ import { i as translator, r as languageOf$1, t as trimCharacters } from "./text-CzqhC8sT.js";
4
+ import { T as estimateAnswer, _ as estimateTokens, a as childTrace, b as addTokens, g as blockText, h as requestsOf, l as runChild, n as childModel, r as childSampling, v as tokensOf, y as NO_TOKENS } from "./child-C9nPIy9j.js";
5
5
  import { dirname, join } from "node:path";
6
+ import { DAY, ENGAGEMENT_GRACE, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, describeValue, holidaysOn, inAudience, isSessionId, itemKey, localTime, locationKey, nextOccurrence, nextTimeOfDay, occurrenceAt, parseInstant, planItemChange, planVariableChange, readCalendar, rollPlain, seasonOf, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
6
7
  import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
8
  import { readFile, stat } from "node:fs/promises";
8
9
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
9
10
  import { defineTool } from "@deepseek-ai/dsh-tools";
10
11
  import { fileURLToPath } from "node:url";
11
12
  import { Service } from "@deepseek-ai/cordis";
12
- import { DAY, ENGAGEMENT_GRACE, ITEM_ACTIONS, MINUTE, SECOND, addLocalDays, agendaAt, announcements, applyItemPlan, changeItem, changeVariable, clockTime, createCharacterTools, createDiceTools, createTools, dayPart, describeDuration, describeInstant, describeValue, holidaysOn, inAudience, isSessionId, itemKey, localTime, locationKey, nextOccurrence, nextTimeOfDay, occurrenceAt, parseInstant, planItemChange, planVariableChange, readCalendar, rollPlain, seasonOf, sessionDatabase, sessionFolder, shownVariables } from "@dsh-agentic-roleplay/state";
13
13
  // ../dsh-roleplay-model/src/trigger.ts
14
14
  /** The reasons the world author is asked to make something up in play; a trigger that has the author make a person names one of them. */
15
15
  const AUTHORING_NEEDS = [
@@ -45,6 +45,153 @@ const PLOT_NUDGE_MODES = [
45
45
  "escalation",
46
46
  "breathing_room"
47
47
  ];
48
+ // src/host/clock/story-clock.ts
49
+ var ClockError = class extends Error {};
50
+ /** A moment as it is told next to `now`: the clock when it is the same day, the date as well when it is not. */
51
+ function describeWhen(instant, now, zone, language = "en") {
52
+ const a = localTime(instant, zone);
53
+ const b = localTime(now, zone);
54
+ return a.year === b.year && a.month === b.month && a.day === b.day ? clockTime(instant, zone) : describeInstant(instant, zone, language);
55
+ }
56
+ /**
57
+ * The time in a sentence: the day and date, the clock, and the part of the day; and, when the world has a calendar, the season and the holidays that
58
+ * fall on the day.
59
+ */
60
+ function describeTime(time, language = "en") {
61
+ const { calendar } = time;
62
+ const tr = translator(language);
63
+ const base = `${describeInstant(time.now, time.zone, language)} (${tr(dayPart(localTime(time.now, time.zone).minuteOfDay))})`;
64
+ if (calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north") return base;
65
+ const day = addLocalDays(time.now, time.zone, 0);
66
+ const holidays = holidaysOn(calendar, day).map((holiday) => holiday.name);
67
+ return `${base}${tr(", ")}${tr(seasonOf(day, calendar.hemisphere))}${holidays.length === 0 ? "" : `${tr("; ")}${tr("today is {holidays}", { holidays: holidays.join(tr(", ")) })}`}`;
68
+ }
69
+ /** The time zone the story is read in. */
70
+ const zoneOf = (config) => config.timeZone === "" ? "UTC" : config.timeZone;
71
+ /** The clock, started when a session has none yet, and detached from the real clock when the settings say so. The mode the story has is the one it keeps otherwise. */
72
+ function ensure(session, config, turn, wall) {
73
+ const current = session.clock.get();
74
+ if (current === void 0) {
75
+ session.clock.start(config.mode, config.mode === "real" ? wall : Math.floor(wall / MINUTE) * MINUTE);
76
+ return session.clock.get() ?? {
77
+ mode: config.mode,
78
+ now: wall
79
+ };
80
+ }
81
+ if (current.mode !== "real" || config.mode !== "simulated") return current;
82
+ session.clock.resync("simulated", Math.max(current.now, wall), turn, "the story's time was detached from the real clock");
83
+ return session.clock.get() ?? current;
84
+ }
85
+ function timeOf(session, state, config) {
86
+ const calendar = session.metadata === void 0 ? void 0 : readCalendar(session.metadata);
87
+ return {
88
+ mode: state.mode,
89
+ now: state.now,
90
+ zone: zoneOf(config),
91
+ ...calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north" ? {} : { calendar }
92
+ };
93
+ }
94
+ /** What time it is, without letting any pass. */
95
+ function readTime(session, config, turn, wall) {
96
+ return session.transaction(() => timeOf(session, ensure(session, config, turn, wall), config));
97
+ }
98
+ /**
99
+ * The start of a turn. Following the wall clock, the time since the last turn passed outside the story:
100
+ * `away` says how long.
101
+ */
102
+ function beginTurn(session, config, turn, wall) {
103
+ return session.transaction(() => {
104
+ const state = ensure(session, config, turn, wall);
105
+ if (state.mode === "real" && wall > state.now) {
106
+ session.clock.advance({
107
+ to: wall,
108
+ turn,
109
+ round: 0,
110
+ kind: "real",
111
+ reason: "between turns"
112
+ });
113
+ return {
114
+ time: timeOf(session, {
115
+ mode: "real",
116
+ now: wall
117
+ }, config),
118
+ away: wall - state.now
119
+ };
120
+ }
121
+ return { time: timeOf(session, state, config) };
122
+ });
123
+ }
124
+ /**
125
+ * A round passes. Simulated, it takes what the game master said (or the default), and at least as long as the
126
+ * journey the player's character made (`minimum`); following the wall clock, it takes as long as it took.
127
+ */
128
+ function endRound(session, config, turn, round, wall, stated, minimum) {
129
+ return session.transaction(() => {
130
+ const state = ensure(session, config, turn, wall);
131
+ if (state.mode === "real") {
132
+ const to = Math.max(state.now, wall);
133
+ session.clock.advance({
134
+ to,
135
+ turn,
136
+ round,
137
+ kind: "real"
138
+ });
139
+ return {
140
+ from: state.now,
141
+ to,
142
+ zone: zoneOf(config)
143
+ };
144
+ }
145
+ const took = Math.max(stated ?? config.roundSeconds, minimum ?? 0) * SECOND;
146
+ session.clock.advance({
147
+ to: state.now + took,
148
+ turn,
149
+ round,
150
+ kind: "elapsed"
151
+ });
152
+ return {
153
+ from: state.now,
154
+ to: state.now + took,
155
+ zone: zoneOf(config)
156
+ };
157
+ });
158
+ }
159
+ /**
160
+ * Skip ahead in the story's own time.
161
+ * @throws {ClockError} when time follows the wall clock, the request is not one, or it asks for more than the chat allows.
162
+ */
163
+ function skipTime(session, config, turn, round, wall, request) {
164
+ return session.transaction(() => {
165
+ const state = ensure(session, config, turn, wall);
166
+ if (state.mode === "real") throw new ClockError("the story's time follows the wall clock, so it cannot be skipped");
167
+ const zone = zoneOf(config);
168
+ const reason = request.reason.trim();
169
+ if (reason === "") throw new ClockError("say what happens in the time that passes (reason)");
170
+ let to;
171
+ if ("byMinutes" in request) {
172
+ if (!Number.isInteger(request.byMinutes) || request.byMinutes < 1) throw new ClockError("by_minutes must be a whole number of minutes, at least 1");
173
+ to = state.now + request.byMinutes * MINUTE;
174
+ } else try {
175
+ to = nextTimeOfDay(state.now, zone, request.untilTime, request.daysLater);
176
+ } catch (error) {
177
+ throw new ClockError(error instanceof RangeError ? error.message : String(error));
178
+ }
179
+ if (to - state.now > config.maxSkipDays * DAY) throw new ClockError(`that is ${Math.round((to - state.now) / DAY)} days from now (${describeInstant(state.now, zone)}), more than the ${config.maxSkipDays} days this chat allows in one skip`);
180
+ session.clock.advance({
181
+ to,
182
+ turn,
183
+ round,
184
+ kind: "skip",
185
+ reason
186
+ });
187
+ return {
188
+ from: state.now,
189
+ to,
190
+ zone,
191
+ reason
192
+ };
193
+ });
194
+ }
48
195
  // src/host/sessions/errors.ts
49
196
  var WorldNotFoundError = class extends Error {};
50
197
  /** The world cannot be played as it is; `problems` say what to fix. */
@@ -559,6 +706,43 @@ function plotReferenceProblems(plots, entities) {
559
706
  const known = new Set(entities);
560
707
  return plots.flatMap((plot) => plot.participants.filter((participant) => !known.has(participant)).map((participant) => `plot "${plot.id}" names unknown participant "${participant}"`));
561
708
  }
709
+ // src/host/sessions/usage.ts
710
+ const KEY$5 = "usage";
711
+ const isCount = (value) => typeof value === "object" && value !== null && [
712
+ "input",
713
+ "cached",
714
+ "output"
715
+ ].every((field) => typeof value[field] === "number");
716
+ const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
717
+ /** What each turn used, oldest first. The record belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
718
+ function readUsage(session) {
719
+ const stored = session.metadata.getValue(KEY$5);
720
+ return Array.isArray(stored) ? stored.filter(isUsage) : [];
721
+ }
722
+ /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
723
+ function addUsage(session, turn, who, tokens, masterMs) {
724
+ const all = readUsage(session);
725
+ const at = all.findIndex((entry) => entry.turn === turn);
726
+ const entry = at === -1 ? {
727
+ turn,
728
+ master: NO_TOKENS,
729
+ helpers: NO_TOKENS,
730
+ runs: 0
731
+ } : all[at];
732
+ const next = who === "master" ? {
733
+ ...entry,
734
+ master: addTokens(entry.master, tokens),
735
+ ...masterMs === void 0 ? {} : { masterMs: (entry.masterMs ?? 0) + masterMs }
736
+ } : {
737
+ ...entry,
738
+ helpers: addTokens(entry.helpers, tokens),
739
+ runs: entry.runs + 1
740
+ };
741
+ if (at === -1) all.push(next);
742
+ else all[at] = next;
743
+ all.sort((a, b) => a.turn - b.turn);
744
+ session.metadata.setValue(KEY$5, all);
745
+ }
562
746
  // src/host/translate/language.ts
563
747
  const STORY_LANGUAGES = ["en", "zh"];
564
748
  /** Less than this many letters of either script is too little to tell a language. */
@@ -841,153 +1025,6 @@ function parseCharacterAction(value) {
841
1025
  ...told === "" ? {} : { account: told }
842
1026
  };
843
1027
  }
844
- // src/host/clock/story-clock.ts
845
- var ClockError = class extends Error {};
846
- /** A moment as it is told next to `now`: the clock when it is the same day, the date as well when it is not. */
847
- function describeWhen(instant, now, zone, language = "en") {
848
- const a = localTime(instant, zone);
849
- const b = localTime(now, zone);
850
- return a.year === b.year && a.month === b.month && a.day === b.day ? clockTime(instant, zone) : describeInstant(instant, zone, language);
851
- }
852
- /**
853
- * The time in a sentence: the day and date, the clock, and the part of the day; and, when the world has a calendar, the season and the holidays that
854
- * fall on the day.
855
- */
856
- function describeTime(time, language = "en") {
857
- const { calendar } = time;
858
- const tr = translator(language);
859
- const base = `${describeInstant(time.now, time.zone, language)} (${tr(dayPart(localTime(time.now, time.zone).minuteOfDay))})`;
860
- if (calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north") return base;
861
- const day = addLocalDays(time.now, time.zone, 0);
862
- const holidays = holidaysOn(calendar, day).map((holiday) => holiday.name);
863
- return `${base}${tr(", ")}${tr(seasonOf(day, calendar.hemisphere))}${holidays.length === 0 ? "" : `${tr("; ")}${tr("today is {holidays}", { holidays: holidays.join(tr(", ")) })}`}`;
864
- }
865
- /** The time zone the story is read in. */
866
- const zoneOf = (config) => config.timeZone === "" ? "UTC" : config.timeZone;
867
- /** The clock, started when a session has none yet, and detached from the real clock when the settings say so. The mode the story has is the one it keeps otherwise. */
868
- function ensure(session, config, turn, wall) {
869
- const current = session.clock.get();
870
- if (current === void 0) {
871
- session.clock.start(config.mode, config.mode === "real" ? wall : Math.floor(wall / MINUTE) * MINUTE);
872
- return session.clock.get() ?? {
873
- mode: config.mode,
874
- now: wall
875
- };
876
- }
877
- if (current.mode !== "real" || config.mode !== "simulated") return current;
878
- session.clock.resync("simulated", Math.max(current.now, wall), turn, "the story's time was detached from the real clock");
879
- return session.clock.get() ?? current;
880
- }
881
- function timeOf(session, state, config) {
882
- const calendar = session.metadata === void 0 ? void 0 : readCalendar(session.metadata);
883
- return {
884
- mode: state.mode,
885
- now: state.now,
886
- zone: zoneOf(config),
887
- ...calendar === void 0 || calendar.holidays.length === 0 && calendar.hemisphere === "north" ? {} : { calendar }
888
- };
889
- }
890
- /** What time it is, without letting any pass. */
891
- function readTime(session, config, turn, wall) {
892
- return session.transaction(() => timeOf(session, ensure(session, config, turn, wall), config));
893
- }
894
- /**
895
- * The start of a turn. Following the wall clock, the time since the last turn passed outside the story:
896
- * `away` says how long.
897
- */
898
- function beginTurn(session, config, turn, wall) {
899
- return session.transaction(() => {
900
- const state = ensure(session, config, turn, wall);
901
- if (state.mode === "real" && wall > state.now) {
902
- session.clock.advance({
903
- to: wall,
904
- turn,
905
- round: 0,
906
- kind: "real",
907
- reason: "between turns"
908
- });
909
- return {
910
- time: timeOf(session, {
911
- mode: "real",
912
- now: wall
913
- }, config),
914
- away: wall - state.now
915
- };
916
- }
917
- return { time: timeOf(session, state, config) };
918
- });
919
- }
920
- /**
921
- * A round passes. Simulated, it takes what the game master said (or the default), and at least as long as the
922
- * journey the player's character made (`minimum`); following the wall clock, it takes as long as it took.
923
- */
924
- function endRound(session, config, turn, round, wall, stated, minimum) {
925
- return session.transaction(() => {
926
- const state = ensure(session, config, turn, wall);
927
- if (state.mode === "real") {
928
- const to = Math.max(state.now, wall);
929
- session.clock.advance({
930
- to,
931
- turn,
932
- round,
933
- kind: "real"
934
- });
935
- return {
936
- from: state.now,
937
- to,
938
- zone: zoneOf(config)
939
- };
940
- }
941
- const took = Math.max(stated ?? config.roundSeconds, minimum ?? 0) * SECOND;
942
- session.clock.advance({
943
- to: state.now + took,
944
- turn,
945
- round,
946
- kind: "elapsed"
947
- });
948
- return {
949
- from: state.now,
950
- to: state.now + took,
951
- zone: zoneOf(config)
952
- };
953
- });
954
- }
955
- /**
956
- * Skip ahead in the story's own time.
957
- * @throws {ClockError} when time follows the wall clock, the request is not one, or it asks for more than the chat allows.
958
- */
959
- function skipTime(session, config, turn, round, wall, request) {
960
- return session.transaction(() => {
961
- const state = ensure(session, config, turn, wall);
962
- if (state.mode === "real") throw new ClockError("the story's time follows the wall clock, so it cannot be skipped");
963
- const zone = zoneOf(config);
964
- const reason = request.reason.trim();
965
- if (reason === "") throw new ClockError("say what happens in the time that passes (reason)");
966
- let to;
967
- if ("byMinutes" in request) {
968
- if (!Number.isInteger(request.byMinutes) || request.byMinutes < 1) throw new ClockError("by_minutes must be a whole number of minutes, at least 1");
969
- to = state.now + request.byMinutes * MINUTE;
970
- } else try {
971
- to = nextTimeOfDay(state.now, zone, request.untilTime, request.daysLater);
972
- } catch (error) {
973
- throw new ClockError(error instanceof RangeError ? error.message : String(error));
974
- }
975
- if (to - state.now > config.maxSkipDays * DAY) throw new ClockError(`that is ${Math.round((to - state.now) / DAY)} days from now (${describeInstant(state.now, zone)}), more than the ${config.maxSkipDays} days this chat allows in one skip`);
976
- session.clock.advance({
977
- to,
978
- turn,
979
- round,
980
- kind: "skip",
981
- reason
982
- });
983
- return {
984
- from: state.now,
985
- to,
986
- zone,
987
- reason
988
- };
989
- });
990
- }
991
1028
  // src/host/orchestration/observation.ts
992
1029
  /** What a character takes in where it stands and of what it carries: the place, the ways out and what they lead to, what lies in the open, what it holds. */
993
1030
  function observeSurroundings(session, characterId, turn) {
@@ -1024,7 +1061,7 @@ const NOTE_KINDS = [
1024
1061
  "world"
1025
1062
  ];
1026
1063
  // src/host/sessions/notes.ts
1027
- const KEY$5 = "notes";
1064
+ const KEY$4 = "notes";
1028
1065
  const isNote = (value) => {
1029
1066
  if (typeof value !== "object" || value === null) return false;
1030
1067
  const note = value;
@@ -1032,12 +1069,12 @@ const isNote = (value) => {
1032
1069
  };
1033
1070
  /** The notes of a session, at most one per kind. */
1034
1071
  function readNotes(session) {
1035
- const stored = session.metadata.getValue(KEY$5);
1072
+ const stored = session.metadata.getValue(KEY$4);
1036
1073
  return Array.isArray(stored) ? stored.filter(isNote) : [];
1037
1074
  }
1038
1075
  /** Replaces the note of the same kind. */
1039
1076
  function putNote(session, note) {
1040
- session.metadata.setValue(KEY$5, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1077
+ session.metadata.setValue(KEY$4, [...readNotes(session).filter((existing) => existing.kind !== note.kind), note]);
1041
1078
  }
1042
1079
  /** The most lines one note keeps: what is past it is not told. */
1043
1080
  const MAX_NOTE_LINES = 8;
@@ -1052,7 +1089,7 @@ function addToNote(session, kind, turn, lines) {
1052
1089
  }
1053
1090
  /** Removes every note: they belong to the turn that made them. */
1054
1091
  function clearNotes(session) {
1055
- if (readNotes(session).length > 0) session.metadata.setValue(KEY$5, []);
1092
+ if (readNotes(session).length > 0) session.metadata.setValue(KEY$4, []);
1056
1093
  }
1057
1094
  /**
1058
1095
  * The notes of a session, for the player's screen.
@@ -1113,10 +1150,10 @@ function masterTrace(events) {
1113
1150
  };
1114
1151
  }
1115
1152
  // src/host/triggers/deliver.ts
1116
- const KEY$4 = "triggers.withdrawn";
1153
+ const KEY$3 = "triggers.withdrawn";
1117
1154
  /** Why a note was withdrawn instead of told, by the number of the note. */
1118
1155
  function readWithdrawn(session) {
1119
- const stored = session.metadata.getValue(KEY$4);
1156
+ const stored = session.metadata.getValue(KEY$3);
1120
1157
  if (!Array.isArray(stored)) return {};
1121
1158
  return Object.fromEntries(stored.flatMap((entry) => {
1122
1159
  const { note, reason } = entry ?? {};
@@ -1135,7 +1172,7 @@ function deliverNow(session, notes, clock) {
1135
1172
  note: Number(note),
1136
1173
  reason
1137
1174
  }));
1138
- session.metadata.setValue(KEY$4, [...before, ...withdrawn.map(({ note, reason }) => ({
1175
+ session.metadata.setValue(KEY$3, [...before, ...withdrawn.map(({ note, reason }) => ({
1139
1176
  note: note.id,
1140
1177
  reason
1141
1178
  }))].slice(-100));
@@ -1146,9 +1183,9 @@ function deliverNow(session, notes, clock) {
1146
1183
  }));
1147
1184
  }
1148
1185
  // src/host/triggers/judged.ts
1149
- const KEY$3 = "triggers.judged";
1186
+ const KEY$2 = "triggers.judged";
1150
1187
  function readVerdicts(session) {
1151
- const stored = session.metadata.getValue(KEY$3);
1188
+ const stored = session.metadata.getValue(KEY$2);
1152
1189
  if (typeof stored !== "object" || stored === null || Array.isArray(stored)) return {};
1153
1190
  const verdicts = {};
1154
1191
  for (const [statement, value] of Object.entries(stored)) {
@@ -1162,7 +1199,7 @@ function readVerdicts(session) {
1162
1199
  }
1163
1200
  /** Keeps the verdicts of the given statements as they stand and drops every other: a statement no trigger waits on is no longer judged. */
1164
1201
  function writeVerdicts(session, verdicts, keep) {
1165
- session.metadata.setValue(KEY$3, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1202
+ session.metadata.setValue(KEY$2, Object.fromEntries(Object.entries(verdicts).filter(([statement]) => keep.has(statement))));
1166
1203
  }
1167
1204
  /** For `runTriggers`: a statement is true when its last verdict says so, and false when nobody judged it. */
1168
1205
  const verdictReader = (session) => {
@@ -1296,11 +1333,11 @@ function noteStore(session, settings, clock) {
1296
1333
  };
1297
1334
  }
1298
1335
  // src/host/sessions/trace.ts
1299
- const KEY$2 = "trace";
1336
+ const KEY$1 = "trace";
1300
1337
  const isTrace = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.startedAt === "number";
1301
1338
  /** What the story kept of each turn's work, oldest first. It belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1302
1339
  function readTraces(session) {
1303
- const stored = session.metadata.getValue(KEY$2);
1340
+ const stored = session.metadata.getValue(KEY$1);
1304
1341
  return Array.isArray(stored) ? stored.filter(isTrace) : [];
1305
1342
  }
1306
1343
  /** Adds to a turn's trace what one source of it knows; the sources (the characters' briefs, the scene, the log at the end of the turn) arrive at different times. */
@@ -1319,10 +1356,10 @@ function updateTrace(session, turn, patch, merge) {
1319
1356
  if (at === -1) all.push(next);
1320
1357
  else all[at] = next;
1321
1358
  all.sort((a, b) => a.turn - b.turn);
1322
- session.metadata.setValue(KEY$2, all.slice(-30));
1359
+ session.metadata.setValue(KEY$1, all.slice(-30));
1323
1360
  }
1324
1361
  // src/host/sessions/activity.ts
1325
- const KEY$1 = "activity";
1362
+ const KEY = "activity";
1326
1363
  const isEntry = (value) => {
1327
1364
  if (typeof value !== "object" || value === null) return false;
1328
1365
  const entry = value;
@@ -1330,13 +1367,13 @@ const isEntry = (value) => {
1330
1367
  };
1331
1368
  /** The recorded runs, oldest first. */
1332
1369
  function readActivity(session) {
1333
- const stored = session.metadata.getValue(KEY$1);
1370
+ const stored = session.metadata.getValue(KEY);
1334
1371
  return Array.isArray(stored) ? stored.filter(isEntry) : [];
1335
1372
  }
1336
1373
  /** Files the run and returns the runs that fell off the end of the record to make room. */
1337
1374
  function recordActivity(session, entry) {
1338
1375
  const all = [...readActivity(session), entry];
1339
- session.metadata.setValue(KEY$1, all.slice(-60));
1376
+ session.metadata.setValue(KEY, all.slice(-60));
1340
1377
  return all.slice(0, -60);
1341
1378
  }
1342
1379
  const RUN_FOLDER = "activity";
@@ -1418,43 +1455,6 @@ function recordDecisions(folder, site, report, now = () => /* @__PURE__ */ new D
1418
1455
  writeFileSync(aside, JSON.stringify(stats, null, 2));
1419
1456
  renameSync(aside, target);
1420
1457
  }
1421
- // src/host/sessions/usage.ts
1422
- const KEY = "usage";
1423
- const isCount = (value) => typeof value === "object" && value !== null && [
1424
- "input",
1425
- "cached",
1426
- "output"
1427
- ].every((field) => typeof value[field] === "number");
1428
- const isUsage = (value) => typeof value === "object" && value !== null && typeof value.turn === "number" && typeof value.runs === "number" && isCount(value.master) && isCount(value.helpers);
1429
- /** What each turn used, oldest first. The record belongs to the story's state, so taking the story back takes the turns that no longer count with it. */
1430
- function readUsage(session) {
1431
- const stored = session.metadata.getValue(KEY);
1432
- return Array.isArray(stored) ? stored.filter(isUsage) : [];
1433
- }
1434
- /** Adds tokens to a turn's record: the game master's own, or a helper's run. */
1435
- function addUsage(session, turn, who, tokens, masterMs) {
1436
- const all = readUsage(session);
1437
- const at = all.findIndex((entry) => entry.turn === turn);
1438
- const entry = at === -1 ? {
1439
- turn,
1440
- master: NO_TOKENS,
1441
- helpers: NO_TOKENS,
1442
- runs: 0
1443
- } : all[at];
1444
- const next = who === "master" ? {
1445
- ...entry,
1446
- master: addTokens(entry.master, tokens),
1447
- ...masterMs === void 0 ? {} : { masterMs: (entry.masterMs ?? 0) + masterMs }
1448
- } : {
1449
- ...entry,
1450
- helpers: addTokens(entry.helpers, tokens),
1451
- runs: entry.runs + 1
1452
- };
1453
- if (at === -1) all.push(next);
1454
- else all[at] = next;
1455
- all.sort((a, b) => a.turn - b.turn);
1456
- session.metadata.setValue(KEY, all);
1457
- }
1458
1458
  // src/host/clock/agenda.ts
1459
1459
  const CURSOR = "agenda.cursor";
1460
1460
  const ASKED = "agenda.asked";
@@ -2244,6 +2244,36 @@ function parseRoll(text) {
2244
2244
  reason: body.slice(boundary).trim()
2245
2245
  };
2246
2246
  }
2247
+ // src/shared/wait.ts
2248
+ const UNITS = [
2249
+ [/^(?:m|min|mins|minute|minutes|分钟|分)$/iu, 1],
2250
+ [/^(?:h|hr|hrs|hour|hours|小时|時間|时)$/iu, 60],
2251
+ [/^(?:d|day|days|天|日)$/iu, 1440]
2252
+ ];
2253
+ /**
2254
+ * The wait in a player's message (`/wait 2 hours`, `/wait 30m until the ferry`, `/wait 3天`), or nothing when the message does not start with `/wait`. The time may be missing or
2255
+ * unreadable, and is then `undefined` in `minutes`.
2256
+ */
2257
+ function parseWait(text) {
2258
+ const value = text.trimStart();
2259
+ if (value.slice(0, 5).toLowerCase() !== "/wait" || value.length > 5 && !/\s/u.test(value[5])) return void 0;
2260
+ const body = value.slice(5).trim();
2261
+ const match = /^(\d+(?:\.\d+)?)\s*([\p{L}]+)\s*(.*)$/su.exec(body);
2262
+ if (match === null) return {
2263
+ minutes: void 0,
2264
+ reason: body
2265
+ };
2266
+ const unit = UNITS.find(([pattern]) => pattern.test(match[2]));
2267
+ if (unit === void 0) return {
2268
+ minutes: void 0,
2269
+ reason: body
2270
+ };
2271
+ const minutes = Math.round(Number(match[1]) * unit[1]);
2272
+ return {
2273
+ minutes: minutes >= 1 && minutes <= 525600 ? minutes : void 0,
2274
+ reason: match[3].trim()
2275
+ };
2276
+ }
2247
2277
  // src/host/agents/repeat-guard.ts
2248
2278
  /**
2249
2279
  * Keeps an agent that is stuck from making the same call again and again (found live: an assistant made one create-and-list pair 47 times in a review, a game master repeated one
@@ -2361,7 +2391,7 @@ function characterRunner(deps) {
2361
2391
  turn: request.turn,
2362
2392
  policy: settings.memory,
2363
2393
  queryVector: deps.store.queryVector
2364
- }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)) : [];
2394
+ }), request.member.character.id).filter((tool) => toolEnabled(settings.tools, "characters", tool.name)).map((tool) => notingEmpty(tool, deps.store, request.turn, request.member.character.name)) : [];
2365
2395
  const background = (request.knowledge?.lore.length ?? 0) > 0 && tools.some((tool) => tool.name === "recall_my_lore");
2366
2396
  const external = externalGiven(deps.parent.ctx.tools, settings.tools, "characters");
2367
2397
  const named = request.member.character.tier === "background" && settings.models.background.trim() !== "" ? settings.models.background : settings.models.characters;
@@ -2370,7 +2400,7 @@ function characterRunner(deps) {
2370
2400
  signal,
2371
2401
  sampling: childSampling(settings, "characters", answerEstimate(settings.prompts.language, request.away === true)),
2372
2402
  ...childModel(settings, "characters", named),
2373
- trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named),
2403
+ trace: childTrace(deps.store, "characters", request.member.character.name, recalledOf(request), named, request.away === true ? "off stage" : void 0),
2374
2404
  reasoningEffort: deps.store.settings().reasoning.children,
2375
2405
  persona: brief.persona,
2376
2406
  prompt: brief.prompt,
@@ -2383,6 +2413,24 @@ function characterRunner(deps) {
2383
2413
  }));
2384
2414
  };
2385
2415
  }
2416
+ /** A look-up that finds nothing is kept in the turn's trace: it is where the world lacks what a character reached for. */
2417
+ function notingEmpty(tool, store, turn, character) {
2418
+ return {
2419
+ ...tool,
2420
+ async execute(args, exec) {
2421
+ const found = await tool.execute(args, exec);
2422
+ const about = args.about;
2423
+ if (Array.isArray(found) && found.length === 0 && typeof about === "string" && about.trim() !== "") try {
2424
+ store.recordTrace?.(turn, {}, (current) => ({ missing: [...current.missing ?? [], {
2425
+ character,
2426
+ tool: tool.name,
2427
+ about: about.trim().slice(0, 120)
2428
+ }].slice(-40) }));
2429
+ } catch {}
2430
+ return found;
2431
+ }
2432
+ };
2433
+ }
2386
2434
  const BACKGROUND_CHECK = "before you answer: does this moment touch your own past, skills, training, secrets or what you know of a person or place? If it does, read that background first with recall_my_lore (about: the subject) and answer from it; if it does not, submit the same answer again unchanged";
2387
2435
  /** The model decides whether the moment touches its background; asking once at the point of answering is what makes it decide. */
2388
2436
  function submitGate(language, background) {
@@ -3547,6 +3595,7 @@ function installHooks(ctx, deps) {
3547
3595
  });
3548
3596
  ctx.on("session/event", (session, event) => {
3549
3597
  if (event.type !== "turn/end" || session.header.origin === "subagent" || roleplaySessionOf(session.id) === void 0) return;
3598
+ ctx.roleplayOrchestration.recovery.clear(session.id);
3550
3599
  timelines.ended(session.id, session, event.seq);
3551
3600
  const events = session.snapshotEvents();
3552
3601
  const began = events.findLastIndex((entry) => entry.type === "turn/start");
@@ -3580,6 +3629,14 @@ function installHooks(ctx, deps) {
3580
3629
  }
3581
3630
  agent.steer(notice(`You may not end the turn yet: ${missing}.`));
3582
3631
  });
3632
+ ctx.on("agent/request-error", async ({ agent, turn, failure }, next) => {
3633
+ const owner = ownerOf(agent, turn);
3634
+ if (owner !== void 0 && ctx.roleplayOrchestration.recovery.retry(owner.chat, turn, failure)) {
3635
+ ctx.logger.warn(`roleplay: ${owner.chat} turn ${turn}: the game master's call could not be read, running the step again`);
3636
+ return { kind: "retry" };
3637
+ }
3638
+ return next();
3639
+ });
3583
3640
  ctx.on("agent/pre-step", async (payload, next) => {
3584
3641
  const decision = await next();
3585
3642
  const owner = ownerOf(payload.agent, payload.turn);
@@ -3591,9 +3648,10 @@ function installHooks(ctx, deps) {
3591
3648
  if (decision.kind !== "enter" || payload.step !== 1) return decision;
3592
3649
  if (owner === void 0 || store === void 0) return decision;
3593
3650
  const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
3594
- if (!store.settings().background.concurrent) await engine.quiesce(owner.chat);
3651
+ if (!store.settings().background.concurrent) await engine.quiesce(owner.chat, { skipOptional: true });
3595
3652
  await ctx.roleplayOrchestration.unitFree(owner.chat);
3596
- await timelines.begin(owner.chat, payload.turn, text);
3653
+ const began = await timelines.begin(owner.chat, payload.turn, text);
3654
+ deps.rolls?.begin(owner.chat, store.story.metadata.get().id, began.parent);
3597
3655
  const cast = store.cast();
3598
3656
  const ooc = parseOoc(text);
3599
3657
  const command = ooc === void 0 ? /^\/([\p{L}\p{N}_]+)/u.exec(text.trim())?.[1] : void 0;
@@ -3676,7 +3734,7 @@ function installHooks(ctx, deps) {
3676
3734
  if (rules.length > 0) addLine("rules", store.text("roleplay/rules", { rules: rules.map((rule) => `- ${rule}`).join("\n") }));
3677
3735
  const wanted = ooc === void 0 ? parseRoll(text) : void 0;
3678
3736
  if (wanted !== void 0) try {
3679
- const made = rollPlain(wanted.expression);
3737
+ const made = rollPlain(wanted.expression, deps.rolls?.roller(owner.chat));
3680
3738
  const roll = store.story.dice.record({
3681
3739
  turn: payload.turn,
3682
3740
  expression: made.expression,
@@ -3698,6 +3756,19 @@ function installHooks(ctx, deps) {
3698
3756
  engine.skip(owner);
3699
3757
  lines.push(store.text("roleplay/input-refused", { reason: error instanceof Error ? error.message : String(error) }));
3700
3758
  }
3759
+ const waiting = ooc === void 0 && wanted === void 0 ? parseWait(text) : void 0;
3760
+ if (waiting !== void 0) {
3761
+ const clock = store.settings().clock;
3762
+ const refusal = clock.mode === "real" ? tr("this chat follows the clock on the wall, so time cannot be skipped") : waiting.minutes === void 0 ? tr("say how long, for example /wait 2 hours or /wait 30 minutes until the ferry") : waiting.minutes > clock.maxSkipDays * 1440 ? tr("that is more than the {days} days this chat allows in one skip", { days: clock.maxSkipDays }) : void 0;
3763
+ if (refusal !== void 0) {
3764
+ engine.skip(owner);
3765
+ lines.push(store.text("roleplay/input-refused", { reason: refusal }));
3766
+ } else addLine("wait", tr("The player lets {minutes} minutes pass{reason}. Move the story's time on by that much with advance_time, and let the world move meanwhile as it would: characters keep to their days, and you ask only those the time reaches. Stop sooner, at the moment it happens, if something comes up that the player must decide or could not sleep through, say what, and let the player act. Then narrate what the player perceived in the time that passed. You may play at most {rounds} rounds for this.", {
3767
+ minutes: waiting.minutes,
3768
+ reason: waiting.reason === "" ? "" : ` (${waiting.reason})`,
3769
+ rounds: store.settings().maxRounds
3770
+ }));
3771
+ }
3701
3772
  if (ooc !== void 0 && ooc.request !== "") lines.push(store.text(ooc.question ? "roleplay/ask-question" : "roleplay/ooc-command", { request: ooc.request }));
3702
3773
  if (ooc !== void 0 && ooc.request === "") {
3703
3774
  engine.skip(owner);
@@ -3717,6 +3788,6 @@ function installHooks(ctx, deps) {
3717
3788
  };
3718
3789
  });
3719
3790
  }
3720
- export { PromptLibrary as $, RESULTS as A, PLOTS_FILE_NAME as B, notesOfSession as C, describeTime as D, ClockError as E, LANGUAGE_NAMES as F, commandFlagKey as G, parsePlotsFile as H, STORY_LANGUAGES as I, Reader as J, commandsOf as K, isStoryLanguage as L, PLOTS_METADATA_KEY as M, plotProgressOf as N, describeWhen as O, populatePlots as P, PROMPTS_FOLDER as Q, textLanguage as R, addToNote as S, observeAsPlayer as T, plotReferenceProblems as U, loadPlots as V, COMMANDS_KEY as W, errorMessage as X, formatIssue as Y, LANGUAGE_FOLDER as Z, readRunDetail as _, externalWithheld as a, shippedLanguages as at, writeVerdicts as b, record as c, AgentUnavailableError as ct, guardRepeatedCalls as d, ReflectionRefusedError as dt, copyWorldPrompts as et, MAX_OOC_ANSWER as f, SessionArchivedError as ft, readActivity as g, COMPARISONS as gt, readDecisionStats as h, AUTHORING_NEEDS as ht, externalTools as i, promptProblem as it, answerLimits as j, zoneOf as k, characterRunner as l, InvalidStartError as lt, readUsage as m, WorldNotFoundError as mt, installHooks as n, languageOf as nt, PREVIEW_TOOL as o, shippedPromptsDirectory as ot, storesOf as p, SessionNotFoundError as pt, readDocument as q, externalGiven as r, listFiles as rt, createTools$1 as s, shippedText as st, externalToolLimit as t, inheritPrompts as tt, toolEnabled as u, InvalidWorldError as ut, readTraces as v, readNotes as w, readWithdrawn as x, readVerdicts as y, wrongLanguage as z };
3791
+ export { listFiles as $, LANGUAGE_NAMES as A, COMMANDS_KEY as B, readNotes as C, PLOTS_METADATA_KEY as D, answerLimits as E, readUsage as F, formatIssue as G, commandsOf as H, PLOTS_FILE_NAME as I, PROMPTS_FOLDER as J, errorMessage as K, loadPlots as L, isStoryLanguage as M, textLanguage as N, plotProgressOf as O, wrongLanguage as P, languageOf as Q, parsePlotsFile as R, notesOfSession as S, RESULTS as T, readDocument as U, commandFlagKey as V, Reader as W, copyWorldPrompts as X, PromptLibrary as Y, inheritPrompts as Z, readTraces as _, externalWithheld as a, InvalidStartError as at, readWithdrawn as b, record as c, SessionArchivedError as ct, guardRepeatedCalls as d, ClockError as dt, promptProblem as et, MAX_OOC_ANSWER as f, describeTime as ft, readRunDetail as g, COMPARISONS as gt, readActivity as h, AUTHORING_NEEDS as ht, externalTools as i, AgentUnavailableError as it, STORY_LANGUAGES as j, populatePlots as k, characterRunner as l, SessionNotFoundError as lt, readDecisionStats as m, zoneOf as mt, installHooks as n, shippedPromptsDirectory as nt, PREVIEW_TOOL as o, InvalidWorldError as ot, storesOf as p, describeWhen as pt, LANGUAGE_FOLDER as q, externalGiven as r, shippedText as rt, createTools$1 as s, ReflectionRefusedError as st, externalToolLimit as t, shippedLanguages as tt, toolEnabled as u, WorldNotFoundError as ut, readVerdicts as v, observeAsPlayer as w, addToNote as x, writeVerdicts as y, plotReferenceProblems as z };
3721
3792
 
3722
- //# sourceMappingURL=hooks-DTjHWTfx.js.map
3793
+ //# sourceMappingURL=hooks-BpLN_hhT.js.map