@dsh-agentic-roleplay/core 0.3.6 → 0.4.1

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 (49) hide show
  1. package/lib/{tools-Dy1fgP6B.js → authoring-tools-C2BHkEFP.js} +129 -25
  2. package/lib/authoring.js +7 -5
  3. package/lib/{child-CFjnaTZt.js → child-DsixtqTw.js} +94 -2
  4. package/lib/client.js +3758 -2276
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +3 -2
  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-BBgciEEK.js → hooks-CHmUksFS.js} +1963 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +847 -254
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/{lorebook-author-tools-Bj31z1cu.js → lorebook-author-tools-CaT74Q7v.js} +118 -43
  15. package/lib/lorebook-authoring.js +5 -3
  16. package/lib/{settings-CA6icLL_.js → narration-DstnwrvX.js} +148 -2
  17. package/lib/orchestration.js +344 -37
  18. package/lib/{pack-jail-2XztyYAX.js → pack-jail-CEDDI4Xw.js} +170 -13
  19. package/lib/{packs-xHRCcGdb.js → packs-DB_9xiCp.js} +7 -4
  20. package/lib/{presenter-agent-DnNEG_Mn.js → presenter-agent-Gu34bZwd.js} +6 -6
  21. package/lib/preset-BL1d40oG.js +242 -0
  22. package/lib/{preset-author-tools-BxycmoAr.js → preset-author-tools-B2wZXKZo.js} +7 -7
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-gkBWAiVb.js → presets-Dc15L6OU.js} +9 -26
  25. package/lib/{reflection-q0UpwXlx.js → reflection-BWMVdHhR.js} +51 -17
  26. package/package.json +2 -2
  27. package/packs/scene/map.html +1 -0
  28. package/packs/scene/strip.html +1 -0
  29. package/prompts/en/import/lorebook.md +2 -1
  30. package/prompts/en/import/style.md +1 -0
  31. package/prompts/en/lorebook/procedure.md +1 -1
  32. package/prompts/en/preset/procedure.md +1 -1
  33. package/prompts/en/roleplay/character-lookup.md +1 -0
  34. package/prompts/en/roleplay/game-master.md +1 -1
  35. package/prompts/en/roleplay/record-keeper.md +3 -3
  36. package/prompts/en/world/procedure.md +1 -1
  37. package/prompts/zh/import/lorebook.md +2 -1
  38. package/prompts/zh/import/style.md +1 -0
  39. package/prompts/zh/lorebook/procedure.md +1 -1
  40. package/prompts/zh/preset/procedure.md +1 -1
  41. package/prompts/zh/roleplay/character-lookup.md +1 -0
  42. package/prompts/zh/roleplay/game-master.md +1 -1
  43. package/prompts/zh/roleplay/record-keeper.md +3 -3
  44. package/prompts/zh/world/procedure.md +1 -1
  45. package/lib/hooks-DkwFGtNH.js +0 -1060
  46. package/lib/language-BgyxtB2h.js +0 -38
  47. package/lib/load-CVwJjIJ5.js +0 -486
  48. package/lib/narration-DK2kiIjE.js +0 -141
  49. package/lib/preset-D0FMSeZ9.js +0 -59
@@ -1,3 +1,4 @@
1
+ import { g as withoutExtension, h as trimCharacters } from "./child-DsixtqTw.js";
1
2
  import { dirname, extname, join } from "node:path";
2
3
  import { existsSync } from "node:fs";
3
4
  import { randomUUID } from "node:crypto";
@@ -24,7 +25,7 @@ function norm(name) {
24
25
  /** A file-safe key from a name: the letters and digits of any script joined by hyphens; `fallback` when nothing is left. */
25
26
  /** An id made of the letters and digits of a name, in whatever script it is written; a name with none gets the fallback. */
26
27
  function slug(name, fallback) {
27
- const key = name.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60).replace(/-+$/g, "");
28
+ const key = trimCharacters(trimCharacters(name.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "-"), "-").slice(0, 60), "-", "end");
28
29
  return key === "" ? fallback : key;
29
30
  }
30
31
  /** `base`, or `base-2`, `base-3` … the first that `taken` does not hold; the key is added to it. */
@@ -294,7 +295,7 @@ function imageExtensionOf(bytes) {
294
295
  }
295
296
  /** A file name made of the letters and digits of the name it came with, in any script. */
296
297
  function libraryName(original, extension, taken) {
297
- const stem = original.replace(/\.[^.]*$/, "").normalize("NFKC").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "image";
298
+ const stem = trimCharacters(withoutExtension(original).normalize("NFKC").replace(/[^\p{L}\p{N}]+/gu, "-"), "-").slice(0, 60) || "image";
298
299
  for (let n = 1;; n += 1) {
299
300
  const name = `${stem}${n === 1 ? "" : `-${n}`}${extension}`;
300
301
  if (!taken(name)) return name;
@@ -331,4 +332,4 @@ async function addToLibrary(sessionFolder, bytes, originalName) {
331
332
  //#endregion
332
333
  export { withPngMetadata as _, inheritImages as a, slug as b, referenceImagePath as c, MEDIA_TYPES as d, mediaTypeOf as f, readPngMetadata as g, writeImageFileMetadata as h, entityImageDirectory as i, sceneImagePath as l, sidecarOf as m, imageExtensionOf as n, nextSceneSerial as o, readImageFileMetadata as p, LIBRARY_FOLDER as r, readImageMetadata as s, addToLibrary as t, writeImage as u, mapLimit as v, uniqueKey as x, norm as y };
333
334
 
334
- //# sourceMappingURL=library-9JB9zw5a.js.map
335
+ //# sourceMappingURL=library-COIktKBa.js.map
@@ -1,82 +1,126 @@
1
- import { Bt as LORE_KINDS, G as withPlayer, It as ImportCardError, St as writeLorebookEntry, U as cleanText, Vt as LORE_SCOPES, W as partsOf, _t as loadLorebook, it as IMPORT_FOLDER, mt as entriesOf, pt as deleteLorebookEntry, t as contextOf, vt as lorebookDirectory, xt as updateLorebookInfo, yt as readLorebook$1 } from "./tools-Dy1fgP6B.js";
2
- import { n as createPresetFromGuidance } from "./presets-gkBWAiVb.js";
3
- import "./settings-CA6icLL_.js";
4
- import { v as shippedPromptsDirectory } from "./load-CVwJjIJ5.js";
5
- import { b as slug, v as mapLimit, x as uniqueKey } from "./library-9JB9zw5a.js";
1
+ import { Bt as ImportCardError, Ct as readLorebook$1, Et as writeLorebookEntry, Gt as LORE_SCOPES, J as withPlayer, K as cleanText, St as lorebookDirectory, Tt as updateLorebookInfo, Wt as LORE_KINDS, _t as deleteLorebookEntry, i as contextOf, q as partsOf, r as MAX_PREVIEW_TEXT, st as IMPORT_FOLDER, vt as entriesOf, xt as loadLorebook } from "./authoring-tools-C2BHkEFP.js";
2
+ import { n as createPresetFromGuidance } from "./presets-Dc15L6OU.js";
3
+ import "./narration-DstnwrvX.js";
4
+ import { tt as shippedPromptsDirectory } from "./hooks-CHmUksFS.js";
5
+ import { b as slug, v as mapLimit, x as uniqueKey } from "./library-COIktKBa.js";
6
6
  import { join } from "node:path";
7
7
  import { existsSync, readFileSync } from "node:fs";
8
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
9
  import { readFile, rm, writeFile } from "node:fs/promises";
10
- //#region src/shared/lorebook-chat.ts
11
- const PREFIX = "lorebook-author-";
12
- /** Stable DSH chat identity for the authoring conversation of one library lorebook. */
13
- function lorebookChatSessionId(name) {
14
- if (name === "") throw new TypeError("lorebook name cannot be empty");
15
- return `${PREFIX}${encodeURIComponent(name)}`;
16
- }
17
- /** The library lorebook named by a dedicated lorebook authoring chat. */
18
- function lorebookOfChat(chatSessionId) {
19
- if (!chatSessionId.startsWith(PREFIX)) return void 0;
20
- try {
21
- const name = decodeURIComponent(chatSessionId.slice(16));
22
- return name === "" ? void 0 : name;
23
- } catch {
24
- return;
25
- }
26
- }
27
- //#endregion
28
10
  //#region src/host/import/lorebook.ts
29
11
  const MAX_ENTRIES = 500;
30
12
  const BATCH_CHARS = 6e3;
31
13
  const BATCH_ENTRIES = 8;
14
+ /** Instructions are short; an entry longer than this that was called one is most likely a fact the model would otherwise throw away. */
15
+ const MAX_STEERING_SOURCE_CHARS = 2e3;
16
+ /** Guidance that keeps less than this share of its entry's length has not kept what the entry asks for. */
17
+ const MIN_STEERING_SHARE = .15;
32
18
  /** The stand-in for the character a card's lorebook speaks of: a lorebook on its own belongs to no character. */
33
19
  const CHARACTER_WORD = "the character";
34
20
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
35
21
  const text = (value) => typeof value === "string" ? value.trim() : "";
36
22
  const strings = (value) => Array.isArray(value) ? value.flatMap((entry) => typeof entry === "string" && entry.trim() !== "" ? [entry.trim()] : []) : typeof value === "string" && value.trim() !== "" ? value.split(",").map((entry) => entry.trim()).filter((entry) => entry !== "") : [];
37
- /** The book of a file: a lorebook export (`entries`), a card (`data.character_book` or `character_book`), or a bare book. */
23
+ /** The book of a file: a lorebook export (`entries`), a wrapped one (`data.entries`, as catalogues serve it), a card (`data.character_book` or `character_book`), or a bare book. */
38
24
  function bookOf(root) {
39
25
  if (isObject(root["entries"]) || Array.isArray(root["entries"])) return root;
40
- const embedded = (isObject(root["data"]) ? root["data"] : void 0)?.["character_book"] ?? root["character_book"];
26
+ const data = isObject(root["data"]) ? root["data"] : void 0;
27
+ if (data !== void 0 && (isObject(data["entries"]) || Array.isArray(data["entries"]))) return data;
28
+ const embedded = data?.["character_book"] ?? root["character_book"];
41
29
  return isObject(embedded) ? embedded : void 0;
42
30
  }
43
- /**
44
- * Reads a lorebook file. Entries that are switched off or empty are left out; macros of the tool that wrote them are replaced.
45
- * @throws {ImportCardError} when the file is not a lorebook, with why.
46
- */
47
- function readLorebook(file, fileName) {
31
+ function parseRoot(file) {
48
32
  let root;
49
33
  try {
50
- root = JSON.parse(file.toString("utf8").replace(/^/, ""));
34
+ root = JSON.parse(file.toString("utf8").replace(/^\uFEFF/, ""));
51
35
  } catch {
52
36
  throw new ImportCardError("the file is not JSON: a lorebook is the .json file SillyTavern exports");
53
37
  }
54
38
  if (!isObject(root)) throw new ImportCardError("the file is not a lorebook: it must be a JSON object");
39
+ return root;
40
+ }
41
+ /** The entries of the file's book as it holds them, in file order. @throws {ImportCardError} when the file holds no book. */
42
+ function rawEntries(root) {
55
43
  const book = bookOf(root);
56
44
  if (book === void 0) throw new ImportCardError("the file holds no lorebook: it needs an \"entries\" list (or a card with a character book)");
57
- const raw = Array.isArray(book["entries"]) ? book["entries"] : isObject(book["entries"]) ? Object.values(book["entries"]) : [];
45
+ return {
46
+ book,
47
+ entries: (Array.isArray(book["entries"]) ? book["entries"] : isObject(book["entries"]) ? Object.values(book["entries"]) : []).filter(isObject)
48
+ };
49
+ }
50
+ const switchedOff = (entry) => entry["disable"] === true || entry["enabled"] === false;
51
+ const entryKeys = (entry) => [...strings(entry["keys"]), ...strings(entry["key"])];
52
+ const nameOf = (book, root, fileName) => text(book["name"]) || text(root["name"]) || fileName.replace(/\.json$/i, "");
53
+ /**
54
+ * Reads a lorebook file. Entries that are switched off or empty are left out; macros of the tool that wrote them are replaced.
55
+ * @throws {ImportCardError} when the file is not a lorebook, with why.
56
+ */
57
+ function readLorebook(file, fileName) {
58
+ const root = parseRoot(file);
59
+ const { book, entries: raw } = rawEntries(root);
58
60
  const entries = [];
59
61
  for (const entry of raw) {
60
- if (!isObject(entry)) continue;
61
- if (entry["disable"] === true || entry["enabled"] === false) continue;
62
+ if (switchedOff(entry)) continue;
62
63
  const content = cleanText(text(entry["content"]), CHARACTER_WORD);
63
64
  if (content === "") continue;
64
- const keys = [...strings(entry["keys"]), ...strings(entry["key"])];
65
65
  entries.push({
66
66
  ref: entries.length,
67
67
  title: text(entry["comment"]) || text(entry["name"]),
68
- keys,
68
+ keys: entryKeys(entry),
69
69
  text: content
70
70
  });
71
71
  }
72
72
  if (entries.length === 0) throw new ImportCardError("the lorebook has no entries that are switched on and hold text");
73
73
  if (entries.length > MAX_ENTRIES) throw new ImportCardError(`the lorebook has ${entries.length} entries; this importer takes at most ${MAX_ENTRIES}`);
74
- const title = text(book["name"]) || text(root["name"]);
75
74
  return {
76
- name: title === "" ? fileName.replace(/\.json$/i, "") : title,
75
+ name: nameOf(book, root, fileName),
77
76
  entries
78
77
  };
79
78
  }
79
+ /** What a lorebook file offers, for the person to choose from: every entry with text, the ones the file has switched off included. @throws {ImportCardError} when the file is not a lorebook. */
80
+ function previewLorebook(file, fileName) {
81
+ const root = parseRoot(file);
82
+ const { book, entries } = rawEntries(root);
83
+ const items = entries.flatMap((entry, index) => {
84
+ const content = cleanText(text(entry["content"]), CHARACTER_WORD);
85
+ if (content === "") return [];
86
+ const keys = entryKeys(entry);
87
+ return [{
88
+ id: String(index),
89
+ title: text(entry["comment"]) || text(entry["name"]) || `#${index + 1}`,
90
+ detail: keys.join(", "),
91
+ text: content.slice(0, MAX_PREVIEW_TEXT),
92
+ chars: content.length,
93
+ enabled: !switchedOff(entry),
94
+ usable: true,
95
+ ...entry["constant"] === true ? { note: "always" } : {}
96
+ }];
97
+ });
98
+ if (items.length === 0) throw new ImportCardError("the lorebook has no entries that hold text");
99
+ return {
100
+ name: nameOf(book, root, fileName),
101
+ items
102
+ };
103
+ }
104
+ /**
105
+ * The file with only the chosen entries in it, all switched on, as if the book never had the others.
106
+ * @throws {ImportCardError} when a chosen entry is not in the file or nothing is chosen.
107
+ */
108
+ function selectEntries(file, enabled, fileName) {
109
+ const root = parseRoot(file);
110
+ const { book, entries } = rawEntries(root);
111
+ const unknown = enabled.filter((id) => !/^\d+$/.test(id) || Number(id) >= entries.length);
112
+ if (unknown.length > 0) throw new ImportCardError(`the lorebook has no entry ${unknown.map((id) => `"${id}"`).join(", ")}`);
113
+ const chosen = [...new Set(enabled.map(Number))].sort((a, b) => a - b).map((index) => ({
114
+ ...entries[index],
115
+ disable: false,
116
+ enabled: true
117
+ }));
118
+ if (chosen.length === 0) throw new ImportCardError("choose at least one entry of the lorebook");
119
+ return Buffer.from(JSON.stringify({
120
+ name: nameOf(book, root, fileName),
121
+ entries: chosen
122
+ }));
123
+ }
80
124
  /** Where a piece of steering text goes: the prose prompts, and the prompts that tell the models how to run the game. */
81
125
  const STEERING_TARGETS = {
82
126
  style: "roleplay/style",
@@ -122,6 +166,10 @@ const DECISIONS_SCHEMA = {
122
166
  type: "string",
123
167
  description: "For knowledge: one sentence saying what the entry tells. Empty otherwise."
124
168
  },
169
+ has_secrets: {
170
+ type: "boolean",
171
+ description: "For knowledge: true when the entry holds anything that not everyone in the world may know: a hidden identity, a secret, a hidden motive, private thoughts, or anything marked hidden or private. Such an entry is never told to everyone. False otherwise."
172
+ },
125
173
  scope: {
126
174
  type: "string",
127
175
  enum: [...LORE_SCOPES],
@@ -148,6 +196,7 @@ const DECISIONS_SCHEMA = {
148
196
  "title",
149
197
  "kind",
150
198
  "summary",
199
+ "has_secrets",
151
200
  "scope",
152
201
  "known_by",
153
202
  "target",
@@ -185,8 +234,11 @@ function problemOf(answer, batch) {
185
234
  if (seen.has(decision.ref)) return `entry ${decision.ref} is decided twice`;
186
235
  seen.add(decision.ref);
187
236
  if (decision.role === "knowledge" && text(decision.title) === "" && batch.find((entry) => entry.ref === decision.ref)?.title === "") return `entry ${decision.ref} is knowledge and has no title: give it one`;
188
- if (decision.role === "knowledge" && decision.scope === "listed" && strings(decision.known_by).length === 0) return `entry ${decision.ref} is listed but names nobody who knows it: use everyone, or name them`;
237
+ if (decision.role === "knowledge" && decision.scope === "listed" && decision.has_secrets !== true && strings(decision.known_by).length === 0) return `entry ${decision.ref} is listed but names nobody who knows it: use everyone, or name them`;
189
238
  if (decision.role === "steering" && (!isSteeringTarget(text(decision.target)) || text(decision.guidance) === "")) return `entry ${decision.ref} is steering: say where it belongs (${Object.keys(STEERING_TARGETS).join(", ")}) and give the guidance`;
239
+ const source = batch.find((entry) => entry.ref === decision.ref);
240
+ if (decision.role === "steering" && source !== void 0 && source.text.length > MAX_STEERING_SOURCE_CHARS) return `entry ${decision.ref} is ${source.text.length} characters long, too long to be an instruction: an entry that describes a person, a place or history is knowledge, and what is thrown away as steering is lost. Make it knowledge, or skip it if it is neither`;
241
+ if (decision.role === "steering" && source !== void 0 && text(decision.guidance).length < source.text.length * MIN_STEERING_SHARE) return `the guidance for entry ${decision.ref} is much shorter than the entry (${text(decision.guidance).length} of ${source.text.length} characters): keep everything the entry asks for, or, if it is not an instruction, make it knowledge`;
190
242
  }
191
243
  const missing = batch.filter((entry) => !seen.has(entry.ref)).map((entry) => entry.ref);
192
244
  return missing.length === 0 ? void 0 : `decide every entry: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} missing`;
@@ -210,6 +262,7 @@ async function classifyEntries(ctx, book) {
210
262
  const result = {
211
263
  entries: [],
212
264
  steering: {},
265
+ steeringFrom: {},
213
266
  notes: []
214
267
  };
215
268
  const taken = /* @__PURE__ */ new Set();
@@ -225,11 +278,13 @@ async function classifyEntries(ctx, book) {
225
278
  if (decision.role === "steering") {
226
279
  const target = text(decision.target);
227
280
  (result.steering[target] ??= []).push(withPlayer(text(decision.guidance)));
281
+ (result.steeringFrom[target] ??= []).push(label);
282
+ result.notes.push(`kept aside as instructions for ${STEERING_TARGETS[target]}: ${label}`);
228
283
  continue;
229
284
  }
230
285
  const title = (text(decision.title) || source.title).slice(0, 100);
231
286
  const kind = LORE_KINDS.includes(decision.kind) ? decision.kind : "other";
232
- const listed = decision.scope === "listed" && strings(decision.known_by).length > 0;
287
+ const listed = decision.has_secrets === true || decision.scope === "listed" && strings(decision.known_by).length > 0;
233
288
  const also = source.keys.length === 0 ? "" : ` Also: ${source.keys.join(", ")}.`;
234
289
  const parts = partsOf(withPlayer(source.text));
235
290
  for (const [part, body] of parts.entries()) result.entries.push({
@@ -247,6 +302,24 @@ async function classifyEntries(ctx, book) {
247
302
  return result;
248
303
  }
249
304
  //#endregion
305
+ //#region src/shared/lorebook-chat.ts
306
+ const PREFIX = "lorebook-author-";
307
+ /** Stable DSH chat identity for the authoring conversation of one library lorebook. */
308
+ function lorebookChatSessionId(name) {
309
+ if (name === "") throw new TypeError("lorebook name cannot be empty");
310
+ return `${PREFIX}${encodeURIComponent(name)}`;
311
+ }
312
+ /** The library lorebook named by a dedicated lorebook authoring chat. */
313
+ function lorebookOfChat(chatSessionId) {
314
+ if (!chatSessionId.startsWith(PREFIX)) return void 0;
315
+ try {
316
+ const name = decodeURIComponent(chatSessionId.slice(16));
317
+ return name === "" ? void 0 : name;
318
+ } catch {
319
+ return;
320
+ }
321
+ }
322
+ //#endregion
250
323
  //#region src/host/authoring/lorebook-author-tools.ts
251
324
  const LOREBOOK_MUTATION_TOOLS = [
252
325
  "write_lorebook_entry",
@@ -502,9 +575,11 @@ function lorebookAuthorTools(reader, settings, prompting, shipped = shippedPromp
502
575
  });
503
576
  }
504
577
  const guidance = Object.fromEntries(Object.entries(made.steering).map(([target, lines]) => [STEERING_TARGETS[target], lines]));
578
+ const from = Object.fromEntries(Object.entries(made.steeringFrom).map(([target, titles]) => [STEERING_TARGETS[target], titles]));
505
579
  if (Object.keys(guidance).length > 0) await writeFile(join(directory, IMPORT_FOLDER, STEERING_FILE), JSON.stringify({
506
580
  source: uploaded.name,
507
- guidance
581
+ guidance,
582
+ from
508
583
  }, null, 2));
509
584
  await rm(join(directory, IMPORT_FOLDER, "lorebook.json"), { force: true });
510
585
  const waiting = Object.keys(guidance);
@@ -614,6 +689,6 @@ async function lorebookApproval(exec, next, state) {
614
689
  };
615
690
  }
616
691
  //#endregion
617
- export { lorebookImportMessage as a, lorebookChatSessionId as c, lorebookAuthorTools as i, lorebookOfChat as l, LorebookReader as n, pendingTargets as o, lorebookApproval as r, readLorebook as s, LOREBOOK_UPLOAD as t };
692
+ export { lorebookImportMessage as a, lorebookOfChat as c, selectEntries as d, lorebookAuthorTools as i, previewLorebook as l, LorebookReader as n, pendingTargets as o, lorebookApproval as r, lorebookChatSessionId as s, LOREBOOK_UPLOAD as t, readLorebook as u };
618
693
 
619
- //# sourceMappingURL=lorebook-author-tools-Bj31z1cu.js.map
694
+ //# sourceMappingURL=lorebook-author-tools-CaT74Q7v.js.map
@@ -1,6 +1,6 @@
1
- import { vt as lorebookDirectory } from "./tools-Dy1fgP6B.js";
2
- import "./load-CVwJjIJ5.js";
3
- import { i as lorebookAuthorTools, l as lorebookOfChat, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-Bj31z1cu.js";
1
+ import { St as lorebookDirectory, n as limitAuthoringAgents } from "./authoring-tools-C2BHkEFP.js";
2
+ import "./hooks-CHmUksFS.js";
3
+ import { c as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-CaT74Q7v.js";
4
4
  import { join } from "node:path";
5
5
  import { existsSync, readdirSync } from "node:fs";
6
6
  //#region src/lorebook-authoring.ts
@@ -10,6 +10,7 @@ const inject = [
10
10
  "roleplayImport",
11
11
  "roleplayPrompts",
12
12
  "roleplayAuthoringLanguages",
13
+ "roleplayAuthoringTools",
13
14
  "tools",
14
15
  "systemPrompt"
15
16
  ];
@@ -37,6 +38,7 @@ function apply(ctx) {
37
38
  rules: false
38
39
  } : pendingTargets(directory);
39
40
  };
41
+ limitAuthoringAgents(ctx, (chat) => lorebookOfChat(chat) === void 0 ? void 0 : "lorebookAuthoring");
40
42
  ctx.on("tools/pre-execute", (exec, next) => lorebookApproval(exec, next, {
41
43
  carries,
42
44
  waiting
@@ -1,3 +1,5 @@
1
+ import { join } from "node:path";
2
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
1
3
  //#region ../dsh-roleplay-model/src/clock.ts
2
4
  /**
3
5
  * How the story's time passes: `simulated` moves only when the story does (the game master says how
@@ -188,6 +190,7 @@ const SETTINGS_SPEC = {
188
190
  context: {
189
191
  limitTokens: integer(0, 1e6, 0),
190
192
  limitRatio: ratio(.1, .9, .6),
193
+ workingTokens: integer(0, 1e6, 0),
191
194
  retainRatio: ratio(.1, .9, .5),
192
195
  shortTermTokens: integer(200, 2e4, 1500),
193
196
  longTermTokens: integer(200, 4e4, 2500)
@@ -205,6 +208,7 @@ const SETTINGS_SPEC = {
205
208
  maxSkipDays: integer(1, 3650, 30)
206
209
  },
207
210
  diagnostics: { keepRuns: flag(false) },
211
+ background: { concurrent: flag(false) },
208
212
  offstage: {
209
213
  perTurn: integer(0, 5, 2),
210
214
  perCharacter: integer(1, 3, 1),
@@ -214,10 +218,17 @@ const SETTINGS_SPEC = {
214
218
  sampling: {
215
219
  master: ratio(0, 2, .7),
216
220
  characters: ratio(0, 2, .8),
221
+ topP: ratio(0, 1, 1),
222
+ topK: integer(0, 1e3, 0),
223
+ minP: ratio(0, 1, 0),
224
+ frequencyPenalty: ratio(-2, 2, 0),
225
+ presencePenalty: ratio(-2, 2, 0),
226
+ repetitionPenalty: ratio(0, 2, 1),
217
227
  suggestions: ratio(0, 2, .2),
218
228
  authoring: ratio(0, 2, .4),
219
229
  records: ratio(0, 2, .1),
220
230
  tools: choice(["auto", "required"], "required"),
231
+ masterMaxTokens: integer(1024, 64e3, 12e3),
221
232
  maxTokens: integer(256, 64e3, 8e3),
222
233
  shortMaxTokens: integer(256, 64e3, 2e3),
223
234
  headroom: ratio(1, 10, 2)
@@ -378,6 +389,141 @@ function parseSettings(value) {
378
389
  };
379
390
  }
380
391
  //#endregion
381
- export { WORLD_RULES_KEY as a, VARIABLE_SUBJECTS as c, parseSwitchboard as i, VARIABLE_VISIBILITIES as l, SETTINGS_SPEC as n, rulesOf as o, parseSettings as r, VARIABLE_KINDS as s, DEFAULT_SETTINGS as t };
392
+ //#region src/host/sessions/settings.ts
393
+ const SETTINGS_FILE = "settings.json";
394
+ const known = /* @__PURE__ */ new Map();
395
+ let childReasoning = "";
396
+ /** The thinking level helpers get when a chat's own setting is empty (the profile's choice); returns the function that takes it back. */
397
+ function useChildReasoning(level) {
398
+ childReasoning = level;
399
+ return () => {
400
+ childReasoning = "";
401
+ };
402
+ }
403
+ /** The settings are not acceptable; `problems` say what to fix. */
404
+ var InvalidSettingsError = class extends Error {
405
+ problems;
406
+ constructor(problems) {
407
+ super(`the settings are not acceptable: ${problems.join("; ")}`);
408
+ this.problems = problems;
409
+ }
410
+ };
411
+ /**
412
+ * The settings of the session in `folder`; a session that has none yet has the defaults.
413
+ * @throws {InvalidSettingsError} when the file exists and is not valid.
414
+ */
415
+ function readSettings(folder) {
416
+ const file = join(folder, SETTINGS_FILE);
417
+ if (!existsSync(file)) return { ...DEFAULT_SETTINGS };
418
+ let value;
419
+ try {
420
+ value = JSON.parse(readFileSync(file, "utf8"));
421
+ } catch (error) {
422
+ throw new InvalidSettingsError([`${SETTINGS_FILE} is not valid JSON (${error instanceof Error ? error.message : String(error)})`]);
423
+ }
424
+ const parsed = parseSettings(value);
425
+ if (!parsed.ok) throw new InvalidSettingsError(parsed.problems);
426
+ return parsed.value;
427
+ }
428
+ /**
429
+ * Store the settings of the session in `folder`, replacing what was there.
430
+ * @throws {InvalidSettingsError} when the value is not acceptable; nothing is written then.
431
+ */
432
+ function writeSettings(folder, value) {
433
+ const parsed = parseSettings(value);
434
+ if (!parsed.ok) throw new InvalidSettingsError(parsed.problems);
435
+ const file = join(folder, SETTINGS_FILE);
436
+ const temporary = `${file}.${process.pid}.tmp`;
437
+ writeFileSync(temporary, `${JSON.stringify(parsed.value, null, 2)}\n`);
438
+ renameSync(temporary, file);
439
+ known.delete(folder);
440
+ return parsed.value;
441
+ }
442
+ /**
443
+ * The settings to use right now. Called before each use, so an edit to the file applies at the
444
+ * next round, step or run without a restart; the file is parsed again only when it changed.
445
+ * A file that is not valid is reported once through `problem` and the last good settings
446
+ * (the defaults when there were none) stay in force, so a typo cannot stop a story in the middle.
447
+ */
448
+ function liveSettings(folder, problem = () => void 0) {
449
+ const value = loadedSettings(folder, problem);
450
+ return value.reasoning.children === "" && childReasoning !== "" ? {
451
+ ...value,
452
+ reasoning: {
453
+ ...value.reasoning,
454
+ children: childReasoning
455
+ }
456
+ } : value;
457
+ }
458
+ function loadedSettings(folder, problem) {
459
+ let modified = -1;
460
+ try {
461
+ modified = statSync(join(folder, SETTINGS_FILE)).mtimeMs;
462
+ } catch {}
463
+ const last = known.get(folder);
464
+ if (last?.modified === modified) return last.value;
465
+ try {
466
+ const value = readSettings(folder);
467
+ known.set(folder, {
468
+ modified,
469
+ value
470
+ });
471
+ return value;
472
+ } catch (error) {
473
+ if (!(error instanceof InvalidSettingsError)) throw error;
474
+ problem(`${error.message} (the last good settings stay in force)`);
475
+ const value = last?.value ?? { ...DEFAULT_SETTINGS };
476
+ known.set(folder, {
477
+ modified,
478
+ value
479
+ });
480
+ return value;
481
+ }
482
+ }
483
+ //#endregion
484
+ //#region src/shared/narration.ts
485
+ const OPEN = "<roleplay-output>";
486
+ const CLOSE = "</roleplay-output>";
487
+ const PREVIEW_OPEN = "<roleplay-preview>";
488
+ const PREVIEW_CLOSE = "</roleplay-preview>";
489
+ /** What the game master shows the player while the characters are still being asked: a scene-setting opening that the delivered output replaces in the view. */
490
+ function encodePreview(text) {
491
+ return `${PREVIEW_OPEN}${JSON.stringify({ text })}${PREVIEW_CLOSE}`;
492
+ }
493
+ function encodeOutput(output) {
494
+ return `${OPEN}${JSON.stringify(output)}${CLOSE}`;
495
+ }
496
+ function isSegment(value) {
497
+ if (typeof value !== "object" || value === null) return false;
498
+ const segment = value;
499
+ if (segment["type"] === "narration") return typeof segment["text"] === "string";
500
+ return segment["type"] === "utterance" && typeof segment["character"] === "string" && typeof segment["name"] === "string" && typeof segment["text"] === "string";
501
+ }
502
+ /** The output encoded in a tool result's text, or nothing when the text carries none. */
503
+ function decodeOutput(text) {
504
+ const start = text.indexOf(OPEN);
505
+ const end = text.indexOf(CLOSE, start + 17);
506
+ if (start < 0 || end < 0) return void 0;
507
+ try {
508
+ const value = JSON.parse(text.slice(start + 17, end));
509
+ const segments = value["segments"];
510
+ if (!Array.isArray(segments) || !segments.every(isSegment) || typeof value["repaired"] !== "boolean") return void 0;
511
+ const ooc = value["ooc"];
512
+ const ruled = typeof ooc === "object" && ooc !== null && typeof ooc["legal"] === "boolean" && typeof ooc["note"] === "string" ? ooc : void 0;
513
+ const timelineNode = typeof value["timelineNode"] === "string" ? value["timelineNode"] : void 0;
514
+ const rolls = Array.isArray(value["rolls"]) ? value["rolls"].filter((entry) => typeof entry === "object" && entry !== null && typeof entry.id === "number" && typeof entry.text === "string" && (entry.by === "agent" || entry.by === "player")) : [];
515
+ return {
516
+ segments,
517
+ repaired: value["repaired"],
518
+ ...ruled === void 0 ? {} : { ooc: ruled },
519
+ ...rolls.length === 0 ? {} : { rolls },
520
+ ...timelineNode === void 0 ? {} : { timelineNode }
521
+ };
522
+ } catch {
523
+ return;
524
+ }
525
+ }
526
+ //#endregion
527
+ export { VARIABLE_VISIBILITIES as _, liveSettings as a, writeSettings as c, parseSettings as d, parseSwitchboard as f, VARIABLE_SUBJECTS as g, VARIABLE_KINDS as h, InvalidSettingsError as i, DEFAULT_SETTINGS as l, rulesOf as m, encodeOutput as n, readSettings as o, WORLD_RULES_KEY as p, encodePreview as r, useChildReasoning as s, decodeOutput as t, SETTINGS_SPEC as u };
382
528
 
383
- //# sourceMappingURL=settings-CA6icLL_.js.map
529
+ //# sourceMappingURL=narration-DstnwrvX.js.map