@dsh-agentic-roleplay/core 0.3.4 → 0.3.6

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 (40) hide show
  1. package/lib/authoring.js +5 -3
  2. package/lib/client.js +3260 -493
  3. package/lib/client.js.map +1 -1
  4. package/lib/{deliver-CpZOxBX5.js → deliver-BBgciEEK.js} +3 -2
  5. package/lib/doctor.js +3 -3
  6. package/lib/{gallery-CtFDL22W.js → gallery-DIEgETzU.js} +2 -2
  7. package/lib/generator-DJ48HxPI.js +145 -0
  8. package/lib/{hooks-KTCR3fNJ.js → hooks-DkwFGtNH.js} +3 -3
  9. package/lib/images.js +4 -3
  10. package/lib/index.js +889 -52
  11. package/lib/language-BgyxtB2h.js +38 -0
  12. package/lib/{generator-B6FxlKOV.js → library-9JB9zw5a.js} +2 -143
  13. package/lib/{language-DWVwi1R7.js → load-CVwJjIJ5.js} +11 -45
  14. package/lib/lorebook-author-tools-Bj31z1cu.js +619 -0
  15. package/lib/lorebook-authoring.js +67 -0
  16. package/lib/orchestration.js +22 -14
  17. package/lib/pack-jail-2XztyYAX.js +1980 -0
  18. package/lib/{packs-BYjrAen6.js → packs-xHRCcGdb.js} +3 -29
  19. package/lib/{presenter-agent-CiEVKcjJ.js → presenter-agent-DnNEG_Mn.js} +4 -3
  20. package/lib/preset-D0FMSeZ9.js +59 -0
  21. package/lib/preset-author-tools-BxycmoAr.js +276 -0
  22. package/lib/preset-authoring.js +53 -0
  23. package/lib/presets-gkBWAiVb.js +374 -0
  24. package/lib/{reflection-waxFg1x-.js → reflection-q0UpwXlx.js} +130 -8
  25. package/lib/{pack-jail-CybSNzxr.js → tools-Dy1fgP6B.js} +454 -2303
  26. package/package.json +4 -2
  27. package/prompts/en/import/lorebook.md +7 -0
  28. package/prompts/en/lorebook/persona.md +1 -0
  29. package/prompts/en/lorebook/procedure.md +1 -0
  30. package/prompts/en/lorebook/welcome.md +1 -0
  31. package/prompts/en/preset/persona.md +1 -0
  32. package/prompts/en/preset/procedure.md +1 -0
  33. package/prompts/en/preset/welcome.md +1 -0
  34. package/prompts/zh/import/lorebook.md +7 -0
  35. package/prompts/zh/lorebook/persona.md +1 -0
  36. package/prompts/zh/lorebook/procedure.md +1 -0
  37. package/prompts/zh/lorebook/welcome.md +1 -0
  38. package/prompts/zh/preset/persona.md +1 -0
  39. package/prompts/zh/preset/procedure.md +1 -0
  40. package/prompts/zh/preset/welcome.md +1 -0
@@ -0,0 +1,374 @@
1
+ import { _ as shippedLanguages, g as promptProblem, h as listFiles, l as LANGUAGE_FOLDER, m as languageOf, u as PROMPTS_FOLDER, v as shippedPromptsDirectory } from "./load-CVwJjIJ5.js";
2
+ import { dirname, join } from "node:path";
3
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
4
+ import { createHash } from "node:crypto";
5
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
6
+ //#region ../dsh-roleplay-model/src/intent.ts
7
+ const INTENT_TYPES = [
8
+ "need",
9
+ "obligation",
10
+ "quest",
11
+ "agenda",
12
+ "aspiration",
13
+ "relationship",
14
+ "habit",
15
+ "reaction"
16
+ ];
17
+ const INTENT_STATUSES = [
18
+ "active",
19
+ "paused",
20
+ "completed",
21
+ "failed",
22
+ "abandoned"
23
+ ];
24
+ const INTENT_HORIZONS = [
25
+ "immediate",
26
+ "short",
27
+ "day",
28
+ "long",
29
+ "open_ended"
30
+ ];
31
+ //#endregion
32
+ //#region src/host/prompts/world-prompts.ts
33
+ /** The prompts that decide how the story is written and who the models are (prose and persona); every other prompt holds rules of the game. */
34
+ const PROSE_PROMPTS = [
35
+ "roleplay/persona",
36
+ "roleplay/style",
37
+ "roleplay/character-style"
38
+ ];
39
+ function shippedFile(shipped, language, id) {
40
+ return [language, "en"].map((name) => join(shipped, name, `${id}.md`)).find((path) => existsSync(path));
41
+ }
42
+ function fileOf(directory, language, id, shipped) {
43
+ const problem = promptProblem(language, id, "x", shipped);
44
+ if (!id.startsWith("roleplay/")) throw new Error(`"${id}" is not a prompt of the story; the ones that can be carried are listed by list_world_prompts`);
45
+ if (problem !== void 0 && problem.startsWith("there is no prompt")) throw new Error(problem);
46
+ return join(directory, PROMPTS_FOLDER, language, `${id}.md`);
47
+ }
48
+ /** Every prompt of the story, in a language, and whether the world carries its own version. */
49
+ function listWorldPrompts(directory, language, shipped = shippedPromptsDirectory()) {
50
+ const tag = languageOf(language);
51
+ return readdirSync(join(shipped, "en"), { withFileTypes: true }).filter((entry) => entry.isDirectory() && ![
52
+ "import",
53
+ "world",
54
+ "preset"
55
+ ].includes(entry.name)).flatMap((entry) => listFiles(join(shipped, "en", entry.name), `${entry.name}/`)).sort().map((id) => ({
56
+ id,
57
+ kind: PROSE_PROMPTS.includes(id) ? "prose" : "rules",
58
+ carried: existsSync(join(directory, PROMPTS_FOLDER, tag, `${id}.md`))
59
+ }));
60
+ }
61
+ /** A prompt as sessions of the world get it: the world's own version, else the shipped text. */
62
+ function readWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
63
+ const tag = languageOf(language);
64
+ const own = fileOf(directory, tag, id, shipped);
65
+ if (existsSync(own)) return {
66
+ id,
67
+ language: tag,
68
+ carried: true,
69
+ text: readFileSync(own, "utf8")
70
+ };
71
+ const original = shippedFile(shipped, tag, id);
72
+ return {
73
+ id,
74
+ language: tag,
75
+ carried: false,
76
+ text: original === void 0 ? "" : readFileSync(original, "utf8")
77
+ };
78
+ }
79
+ /** @throws {Error} when the text is not acceptable for the prompt: see `promptProblem`. */
80
+ async function writeWorldPrompt(directory, language, id, text, shipped = shippedPromptsDirectory()) {
81
+ const tag = languageOf(language);
82
+ const file = fileOf(directory, tag, id, shipped);
83
+ const problem = promptProblem(tag, id, text, shipped);
84
+ if (problem !== void 0) throw new Error(problem);
85
+ await mkdir(dirname(file), { recursive: true });
86
+ const temporary = `${file}.tmp`;
87
+ await writeFile(temporary, text.endsWith("\n") ? text : `${text}\n`);
88
+ await rename(temporary, file);
89
+ }
90
+ /** Moves the world's own version into its `.trash`, so sessions use the shipped one again. @returns where it went. */
91
+ async function deleteWorldPrompt(directory, language, id, shipped = shippedPromptsDirectory()) {
92
+ const tag = languageOf(language);
93
+ const file = fileOf(directory, tag, id, shipped);
94
+ if (!existsSync(file)) throw new Error(`the world carries no prompt "${id}" in ${tag}`);
95
+ const aside = join(directory, ".trash", PROMPTS_FOLDER, tag, `${id}.${Date.now()}.md`);
96
+ await mkdir(dirname(aside), { recursive: true });
97
+ await rename(file, aside);
98
+ await rm(dirname(file), { recursive: false }).catch(() => void 0);
99
+ return aside;
100
+ }
101
+ //#endregion
102
+ //#region src/host/presets/presets.ts
103
+ const PRESETS_FOLDER = "presets";
104
+ const PRESET_FILE = "preset.json";
105
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
106
+ const MAX_TEXT = 300;
107
+ const SAMPLING_KEYS = ["master", "characters"];
108
+ const isPresetName = (name) => NAME.test(name);
109
+ const presetsDirectory = (root) => join(root, PRESETS_FOLDER);
110
+ function presetDirectory(root, name) {
111
+ if (!isPresetName(name)) throw new Error(`"${name}" is not a usable preset name (letters, digits, "-" and "_", up to 64)`);
112
+ return join(presetsDirectory(root), name);
113
+ }
114
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
115
+ function parseHeader(value, problems) {
116
+ if (!isRecord(value)) {
117
+ problems.push(`${PRESET_FILE} must be an object`);
118
+ return { sampling: {} };
119
+ }
120
+ const text = (key) => {
121
+ const field = value[key];
122
+ if (field === void 0 || field === null) return void 0;
123
+ if (typeof field !== "string" || field.length > MAX_TEXT) {
124
+ problems.push(`${PRESET_FILE}: "${key}" must be text of at most ${MAX_TEXT} characters`);
125
+ return;
126
+ }
127
+ return field.trim() || void 0;
128
+ };
129
+ const sampling = {};
130
+ const given = value["sampling"];
131
+ if (given !== void 0 && given !== null) {
132
+ if (!isRecord(given)) problems.push(`${PRESET_FILE}: "sampling" must be an object`);
133
+ else {
134
+ for (const key of Object.keys(given)) if (!SAMPLING_KEYS.includes(key)) problems.push(`${PRESET_FILE}: sampling.${key} is not something a preset sets (${SAMPLING_KEYS.join(", ")})`);
135
+ for (const key of SAMPLING_KEYS) {
136
+ const number = given[key];
137
+ if (number === void 0) continue;
138
+ if (typeof number !== "number" || !Number.isFinite(number) || number < 0 || number > 2) problems.push(`${PRESET_FILE}: sampling.${key} must be a number from 0 to 2`);
139
+ else sampling[key] = number;
140
+ }
141
+ }
142
+ }
143
+ const title = text("title");
144
+ const description = text("description");
145
+ return {
146
+ ...title === void 0 ? {} : { title },
147
+ ...description === void 0 ? {} : { description },
148
+ sampling
149
+ };
150
+ }
151
+ function readHeader(directory, problems) {
152
+ const file = join(directory, PRESET_FILE);
153
+ if (!existsSync(file)) return { sampling: {} };
154
+ let value;
155
+ try {
156
+ value = JSON.parse(readFileSync(file, "utf8"));
157
+ } catch {
158
+ problems.push(`${PRESET_FILE} is not valid JSON`);
159
+ return { sampling: {} };
160
+ }
161
+ return parseHeader(value, problems);
162
+ }
163
+ /** Reads one preset folder, collecting every problem instead of stopping at the first. @throws {Error} when the folder does not exist. */
164
+ function readPreset(directory, name, shipped = shippedPromptsDirectory()) {
165
+ if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
166
+ const problems = [];
167
+ const header = readHeader(directory, problems);
168
+ const files = /* @__PURE__ */ new Map();
169
+ const base = join(directory, PROMPTS_FOLDER);
170
+ if (existsSync(base)) for (const entry of readdirSync(base, { withFileTypes: true })) {
171
+ if (!entry.isDirectory() || !LANGUAGE_FOLDER.test(entry.name)) {
172
+ problems.push(`prompts/${entry.name}: prompts are kept in a folder named by the language, such as en or zh`);
173
+ continue;
174
+ }
175
+ for (const id of listFiles(join(base, entry.name))) {
176
+ const path = `${entry.name}/${id}.md`;
177
+ const text = readFileSync(join(base, path), "utf8");
178
+ const problem = id.startsWith("roleplay/") ? promptProblem(entry.name, id, text, shipped) : `"${id}" is not a prompt of the story`;
179
+ if (problem !== void 0) problems.push(`prompts/${path}: ${problem}`);
180
+ else files.set(path, text);
181
+ }
182
+ }
183
+ if (files.size === 0 && problems.length === 0) problems.push("the preset carries no prompts");
184
+ const paths = [...files.keys()];
185
+ const ids = [...new Set(paths.map((path) => path.slice(path.indexOf("/") + 1, -3)))].sort();
186
+ return {
187
+ summary: {
188
+ name,
189
+ title: header.title ?? name,
190
+ description: header.description ?? "",
191
+ languages: [...new Set(paths.map((path) => path.split("/")[0]))].sort(),
192
+ prompts: ids,
193
+ rules: ids.filter((id) => !PROSE_PROMPTS.includes(id)),
194
+ sampling: header.sampling,
195
+ problems
196
+ },
197
+ files
198
+ };
199
+ }
200
+ /** Every preset in the library; one that cannot be read is listed with its problems. */
201
+ function listPresets(root) {
202
+ const folder = presetsDirectory(root);
203
+ if (!existsSync(folder)) return [];
204
+ return readdirSync(folder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isPresetName(entry.name)).map((entry) => readPreset(join(folder, entry.name), entry.name)).sort((a, b) => a.summary.name.localeCompare(b.summary.name));
205
+ }
206
+ function loadPreset(root, name) {
207
+ return readPreset(presetDirectory(root, name), name);
208
+ }
209
+ const sha = (text) => createHash("sha256").update(text).digest("hex");
210
+ /**
211
+ * Makes a preset of the prose prompts a world carries. Nothing is overwritten.
212
+ * @throws {Error} when the name is taken, the world carries no prose prompt, or what it carries is not acceptable.
213
+ */
214
+ async function savePresetFromWorld(root, worldDirectory, request) {
215
+ const target = presetDirectory(root, request.name);
216
+ if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
217
+ const source = join(worldDirectory, PROMPTS_FOLDER);
218
+ const found = [];
219
+ if (existsSync(source)) {
220
+ for (const entry of readdirSync(source, { withFileTypes: true })) if (entry.isDirectory() && LANGUAGE_FOLDER.test(entry.name)) {
221
+ for (const id of listFiles(join(source, entry.name))) if (PROSE_PROMPTS.includes(id)) found.push({
222
+ language: entry.name,
223
+ id
224
+ });
225
+ }
226
+ }
227
+ if (found.length === 0) throw new Error("the world carries no prose prompts to make a preset of");
228
+ const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
229
+ try {
230
+ for (const { language, id } of found) {
231
+ const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
232
+ await mkdir(dirname(to), { recursive: true });
233
+ await writeFile(to, readFileSync(join(source, language, `${id}.md`), "utf8"));
234
+ }
235
+ const header = {
236
+ ...request.title === void 0 || request.title.trim() === "" ? {} : { title: request.title.trim() },
237
+ ...request.description === void 0 || request.description.trim() === "" ? {} : { description: request.description.trim() },
238
+ ...request.sampling === void 0 || Object.keys(request.sampling).length === 0 ? {} : { sampling: request.sampling }
239
+ };
240
+ await writeFile(join(staging, PRESET_FILE), JSON.stringify(header, null, 2));
241
+ const loaded = readPreset(staging, request.name);
242
+ if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
243
+ await mkdir(presetsDirectory(root), { recursive: true });
244
+ await rename(staging, target);
245
+ return readPreset(target, request.name);
246
+ } finally {
247
+ await rm(staging, {
248
+ recursive: true,
249
+ force: true
250
+ });
251
+ }
252
+ }
253
+ /** Moves a preset out of the library into `<root>/.trash/presets/`. @returns where it went. */
254
+ async function deletePreset(root, name, now = Date.now) {
255
+ const directory = presetDirectory(root, name);
256
+ if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
257
+ const aside = join(root, ".trash", PRESETS_FOLDER, `${name}-${now()}`);
258
+ await mkdir(dirname(aside), { recursive: true });
259
+ await rename(directory, aside);
260
+ return aside;
261
+ }
262
+ function headerFile(title, description, sampling) {
263
+ return `${JSON.stringify({
264
+ ...title === void 0 ? {} : { title },
265
+ ...description === void 0 ? {} : { description },
266
+ ...Object.keys(sampling).length === 0 ? {} : { sampling }
267
+ }, null, 2)}\n`;
268
+ }
269
+ async function writeHeader(directory, text) {
270
+ const file = join(directory, PRESET_FILE);
271
+ await writeFile(`${file}.tmp`, text);
272
+ await rename(`${file}.tmp`, file);
273
+ }
274
+ /** Changes what a preset says about itself. @throws {Error} when the preset does not exist or the change is not acceptable; nothing is written then. */
275
+ async function updatePresetInfo(root, name, change) {
276
+ const directory = presetDirectory(root, name);
277
+ if (!existsSync(directory)) throw new Error(`there is no preset "${name}"`);
278
+ const current = readHeader(directory, []);
279
+ const problems = [];
280
+ const next = parseHeader({
281
+ title: change.title ?? current.title,
282
+ description: change.description ?? current.description,
283
+ sampling: change.sampling ?? current.sampling
284
+ }, problems);
285
+ if (problems.length > 0) throw new Error(problems.join("; "));
286
+ await writeHeader(directory, headerFile(next.title, next.description, next.sampling));
287
+ return readPreset(directory, name);
288
+ }
289
+ /**
290
+ * Makes a preset holding the shipped prose prompts of every language, as a starting point to edit. Nothing is overwritten.
291
+ * @throws {Error} when the name is taken or the information is not acceptable.
292
+ */
293
+ async function createPresetFromShipped(root, request, shipped = shippedPromptsDirectory()) {
294
+ const target = presetDirectory(root, request.name);
295
+ if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
296
+ const problems = [];
297
+ const header = parseHeader({
298
+ title: request.title?.trim(),
299
+ description: request.description?.trim(),
300
+ sampling: request.sampling
301
+ }, problems);
302
+ if (problems.length > 0) throw new Error(problems.join("; "));
303
+ const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
304
+ try {
305
+ for (const language of shippedLanguages(shipped)) for (const id of PROSE_PROMPTS) {
306
+ const from = join(shipped, language, `${id}.md`);
307
+ if (!existsSync(from)) continue;
308
+ const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
309
+ await mkdir(dirname(to), { recursive: true });
310
+ await writeFile(to, readFileSync(from, "utf8"));
311
+ }
312
+ await mkdir(staging, { recursive: true });
313
+ await writeHeader(staging, headerFile(header.title, header.description, header.sampling));
314
+ const loaded = readPreset(staging, request.name);
315
+ if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
316
+ await mkdir(presetsDirectory(root), { recursive: true });
317
+ await rename(staging, target);
318
+ return readPreset(target, request.name);
319
+ } finally {
320
+ await rm(staging, {
321
+ recursive: true,
322
+ force: true
323
+ });
324
+ }
325
+ }
326
+ /** Makes an empty preset folder that the import is about to fill; it has no prompts yet, so it reads as having problems until it does. */
327
+ async function reservePreset(root, name, title) {
328
+ const target = presetDirectory(root, name);
329
+ if (existsSync(target)) throw new Error(`there is already a preset "${name}"`);
330
+ await mkdir(target, { recursive: true });
331
+ await writeHeader(target, headerFile(title.trim().slice(0, MAX_TEXT) || void 0, void 0, {}));
332
+ return target;
333
+ }
334
+ /**
335
+ * Makes a preset that adds guidance to the shipped prompts, in every language the program ships: each prompt keeps its shipped text and the guidance follows it, so that
336
+ * the prompt keeps naming the tools and values it needs. The guidance is the importer's, in the language it was written in.
337
+ * @throws {Error} when the name is taken, there is no guidance, or a prompt would not be acceptable; nothing is made then.
338
+ */
339
+ async function createPresetFromGuidance(root, request, guidance, shipped = shippedPromptsDirectory()) {
340
+ const target = presetDirectory(root, request.name);
341
+ if (existsSync(target)) throw new Error(`there is already a preset "${request.name}"`);
342
+ const ids = Object.keys(guidance).filter((id) => (guidance[id]?.length ?? 0) > 0);
343
+ if (ids.length === 0) throw new Error("there is no guidance to make a preset of");
344
+ const problems = [];
345
+ const header = parseHeader({
346
+ title: request.title?.trim(),
347
+ description: request.description?.trim()
348
+ }, problems);
349
+ if (problems.length > 0) throw new Error(problems.join("; "));
350
+ const staging = join(root, ".install", `preset-${request.name}-${Date.now()}`);
351
+ try {
352
+ for (const language of shippedLanguages(shipped)) for (const id of ids) {
353
+ const base = readWorldPrompt(join(staging, "none"), language, id, shipped).text.trimEnd();
354
+ const to = join(staging, PROMPTS_FOLDER, language, `${id}.md`);
355
+ await mkdir(dirname(to), { recursive: true });
356
+ await writeFile(to, `${base}\n\n${(guidance[id] ?? []).join("\n")}\n`);
357
+ }
358
+ await writeHeader(staging, headerFile(header.title, header.description, {}));
359
+ const loaded = readPreset(staging, request.name);
360
+ if (loaded.summary.problems.length > 0) throw new Error(`the preset would have problems: ${loaded.summary.problems.join("; ")}`);
361
+ await mkdir(presetsDirectory(root), { recursive: true });
362
+ await rename(staging, target);
363
+ return readPreset(target, request.name);
364
+ } finally {
365
+ await rm(staging, {
366
+ recursive: true,
367
+ force: true
368
+ });
369
+ }
370
+ }
371
+ //#endregion
372
+ export { readWorldPrompt as _, isPresetName as a, INTENT_STATUSES as b, presetDirectory as c, savePresetFromWorld as d, sha as f, listWorldPrompts as g, deleteWorldPrompt as h, deletePreset as i, readPreset as l, PROSE_PROMPTS as m, createPresetFromGuidance as n, listPresets as o, updatePresetInfo as p, createPresetFromShipped as r, loadPreset as s, PRESET_FILE as t, reservePreset as u, writeWorldPrompt as v, INTENT_TYPES as x, INTENT_HORIZONS as y };
373
+
374
+ //# sourceMappingURL=presets-gkBWAiVb.js.map
@@ -1,12 +1,14 @@
1
1
  import { r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { i as inheritPacks } from "./packs-BYjrAen6.js";
2
+ import { f as sha, o as listPresets, s as loadPreset } from "./presets-gkBWAiVb.js";
3
3
  import "./settings-CA6icLL_.js";
4
- import { _ as inheritPrompts, a as wrongLanguage } from "./language-DWVwi1R7.js";
5
- import { F as describeWhen, H as languageOf, P as describeTime, U as translator, V as answerLimits } from "./deliver-CpZOxBX5.js";
4
+ import { p as inheritPrompts, u as PROMPTS_FOLDER } from "./load-CVwJjIJ5.js";
5
+ import { F as describeWhen, H as languageOf, P as describeTime, U as translator, V as answerLimits } from "./deliver-BBgciEEK.js";
6
6
  import { a as runChild, i as childTrace, n as childSampling, t as childModel, u as estimateAnswer } from "./child-CFjnaTZt.js";
7
- import { u as inheritImages } from "./generator-B6FxlKOV.js";
8
- import { join } from "node:path";
9
- import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { a as inheritImages } from "./library-9JB9zw5a.js";
8
+ import { a as wrongLanguage } from "./language-BgyxtB2h.js";
9
+ import { i as inheritPacks } from "./packs-xHRCcGdb.js";
10
+ import { dirname, join } from "node:path";
11
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
12
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
11
13
  import { MINUTE, characterKey, describeDuration, locationKey, mentioned, overlap, sessionDatabase, sessionFolder, tokens } from "@dsh-agentic-roleplay/state";
12
14
  //#region ../dsh-roleplay-model/src/memory.ts
@@ -779,6 +781,125 @@ function planMove(timeline, target, surface) {
779
781
  };
780
782
  }
781
783
  //#endregion
784
+ //#region src/host/presets/apply.ts
785
+ /** Which preset a story's prompts came from, and what each copied file held: kept beside the story's database, so that a story can tell its copies from its own edits. */
786
+ const PRESET_RECORD = "preset.json";
787
+ const promptFile = (folder, path) => join(folder, PROMPTS_FOLDER, ...path.split("/"));
788
+ function readRecord(folder) {
789
+ const file = join(folder, PRESET_RECORD);
790
+ if (!existsSync(file)) return void 0;
791
+ let value;
792
+ try {
793
+ value = JSON.parse(readFileSync(file, "utf8"));
794
+ } catch {
795
+ throw new Error(`${file} is damaged`);
796
+ }
797
+ const { name, files } = value ?? {};
798
+ if (typeof name !== "string" || typeof files !== "object" || files === null || !Object.values(files).every((hash) => typeof hash === "string")) throw new Error(`${file} is damaged`);
799
+ return {
800
+ name,
801
+ files
802
+ };
803
+ }
804
+ function writeRecord(folder, record) {
805
+ const file = join(folder, PRESET_RECORD);
806
+ if (record === void 0) {
807
+ rmSync(file, { force: true });
808
+ return;
809
+ }
810
+ const temporary = `${file}.tmp`;
811
+ writeFileSync(temporary, JSON.stringify(record, null, 2));
812
+ renameSync(temporary, file);
813
+ }
814
+ /** Writes the preset's prompts over the story's own. */
815
+ function copyPreset(preset, folder) {
816
+ for (const [path, text] of preset.files) {
817
+ const to = promptFile(folder, path);
818
+ mkdirSync(dirname(to), { recursive: true });
819
+ writeFileSync(to, text);
820
+ }
821
+ }
822
+ /** Notes that the story's prompts came from the preset: only the files that still hold the preset's text count, because the world's own may have replaced the rest. */
823
+ function recordPreset(folder, preset) {
824
+ const files = {};
825
+ for (const [path, text] of preset.files) {
826
+ const own = promptFile(folder, path);
827
+ if (existsSync(own) && readFileSync(own, "utf8") === text) files[path] = sha(text);
828
+ }
829
+ writeRecord(folder, {
830
+ name: preset.summary.name,
831
+ files
832
+ });
833
+ }
834
+ /** Where the story stands against the library. */
835
+ function presetStatus(root, folder) {
836
+ const available = listPresets(root).map((entry) => entry.summary);
837
+ const record = readRecord(folder);
838
+ if (record === void 0) return { available };
839
+ const paths = Object.keys(record.files);
840
+ const edited = paths.some((path) => {
841
+ const file = promptFile(folder, path);
842
+ return !existsSync(file) || sha(readFileSync(file, "utf8")) !== record.files[path];
843
+ });
844
+ let state = edited ? "edited" : "current";
845
+ try {
846
+ const library = loadPreset(root, record.name);
847
+ if (!edited && (library.files.size !== paths.length || paths.some((path) => {
848
+ const text = library.files.get(path);
849
+ return text === void 0 || sha(text) !== record.files[path];
850
+ }))) state = "changed";
851
+ } catch {
852
+ state = "missing";
853
+ }
854
+ return {
855
+ applied: {
856
+ name: record.name,
857
+ state,
858
+ files: paths
859
+ },
860
+ available
861
+ };
862
+ }
863
+ /**
864
+ * Takes the story's copies of its preset out (to `.trash/prompts/` in the story) and, when a preset is named, puts that one in.
865
+ * Prompts the world carried that a preset had replaced are not brought back.
866
+ * @returns the files that were replaced or taken out.
867
+ * @throws {Error} when the named preset has problems or does not exist; nothing is changed then.
868
+ */
869
+ function switchPreset(root, folder, name, now = Date.now) {
870
+ const next = name === void 0 ? void 0 : loadPreset(root, name);
871
+ if (next !== void 0 && next.summary.problems.length > 0) throw new Error(`the preset "${name}" has problems: ${next.summary.problems.join("; ")}`);
872
+ const record = readRecord(folder);
873
+ const touched = new Set(next === void 0 ? [] : next.files.keys());
874
+ for (const path of Object.keys(record?.files ?? {})) touched.add(path);
875
+ const aside = join(folder, ".trash", PROMPTS_FOLDER, String(now()));
876
+ const moved = [];
877
+ for (const path of touched) {
878
+ const file = promptFile(folder, path);
879
+ if (!existsSync(file)) continue;
880
+ const to = join(aside, ...path.split("/"));
881
+ mkdirSync(dirname(to), { recursive: true });
882
+ copyFileSync(file, to);
883
+ moved.push(path);
884
+ }
885
+ for (const path of Object.keys(record?.files ?? {})) {
886
+ const file = promptFile(folder, path);
887
+ rmSync(file, { force: true });
888
+ }
889
+ if (next === void 0) {
890
+ writeRecord(folder, void 0);
891
+ return moved;
892
+ }
893
+ copyPreset(next, folder);
894
+ recordPreset(folder, next);
895
+ return moved;
896
+ }
897
+ /** A branch plays with the preset of the story it was cut from. */
898
+ function inheritPreset(from, to) {
899
+ const file = join(from, PRESET_RECORD);
900
+ if (existsSync(file)) copyFileSync(file, join(to, PRESET_RECORD));
901
+ }
902
+ //#endregion
782
903
  //#region src/host/timeline/service.ts
783
904
  /** The text of the marker that stands for the turns it replaces: never empty, as a model service may refuse an empty message. */
784
905
  const MARKER_TEXT = "(empty message)";
@@ -982,6 +1103,7 @@ var Timelines = class {
982
1103
  try {
983
1104
  await inheritImages(this.folder(from), this.folder(id), branch.timeline.nodes.map((node) => node.id));
984
1105
  inheritPrompts(this.folder(from), this.folder(id));
1106
+ inheritPreset(this.folder(from), this.folder(id));
985
1107
  inheritPacks(this.folder(from), this.folder(id));
986
1108
  const plan = planMove(branch.timeline, branch.timeline.head, [...agent.session.surface.nodes]);
987
1109
  this.reconcile(agent, plan);
@@ -1838,6 +1960,6 @@ function memoryReflector(deps) {
1838
1960
  } };
1839
1961
  }
1840
1962
  //#endregion
1841
- export { whereabouts as a, readTimeline as c, sameWords as d, referent as f, reflectionStatus as i, pathTo as l, memoryReflector as n, TimelineError as o, recordFailure as r, Timelines as s, dueReflection as t, defaultBoundaries as u };
1963
+ export { whereabouts as a, copyPreset as c, switchPreset as d, readTimeline as f, referent as g, sameWords as h, reflectionStatus as i, presetStatus as l, defaultBoundaries as m, memoryReflector as n, TimelineError as o, pathTo as p, recordFailure as r, Timelines as s, dueReflection as t, recordPreset as u };
1842
1964
 
1843
- //# sourceMappingURL=reflection-waxFg1x-.js.map
1965
+ //# sourceMappingURL=reflection-q0UpwXlx.js.map