@dsh-agentic-roleplay/core 0.3.5 → 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 (32) hide show
  1. package/lib/authoring.js +5 -5
  2. package/lib/client.js +1735 -459
  3. package/lib/client.js.map +1 -1
  4. package/lib/{deliver-Cl6bjp7g.js → deliver-BBgciEEK.js} +2 -2
  5. package/lib/doctor.js +3 -3
  6. package/lib/{hooks-DdO_tNhu.js → hooks-DkwFGtNH.js} +3 -3
  7. package/lib/index.js +394 -28
  8. package/lib/{load-Clkl0T7C.js → load-CVwJjIJ5.js} +7 -7
  9. package/lib/lorebook-author-tools-Bj31z1cu.js +619 -0
  10. package/lib/lorebook-authoring.js +67 -0
  11. package/lib/orchestration.js +6 -6
  12. package/lib/{pack-jail-ClMpVc__.js → pack-jail-2XztyYAX.js} +6 -5
  13. package/lib/{packs-BC2A3geF.js → packs-xHRCcGdb.js} +2 -2
  14. package/lib/preset-D0FMSeZ9.js +59 -0
  15. package/lib/{preset-author-tools-Dibp-LY9.js → preset-author-tools-BxycmoAr.js} +22 -16
  16. package/lib/preset-authoring.js +3 -3
  17. package/lib/{presets-DNjNxQL5.js → presets-gkBWAiVb.js} +44 -5
  18. package/lib/{reflection-Bju_LPFn.js → reflection-q0UpwXlx.js} +5 -5
  19. package/lib/{preset-ClQm7KPQ.js → tools-Dy1fgP6B.js} +424 -247
  20. package/package.json +3 -2
  21. package/prompts/en/import/lorebook.md +7 -0
  22. package/prompts/en/lorebook/persona.md +1 -0
  23. package/prompts/en/lorebook/procedure.md +1 -0
  24. package/prompts/en/lorebook/welcome.md +1 -0
  25. package/prompts/en/preset/persona.md +1 -1
  26. package/prompts/en/preset/procedure.md +1 -1
  27. package/prompts/zh/import/lorebook.md +7 -0
  28. package/prompts/zh/lorebook/persona.md +1 -0
  29. package/prompts/zh/lorebook/procedure.md +1 -0
  30. package/prompts/zh/lorebook/welcome.md +1 -0
  31. package/prompts/zh/preset/persona.md +1 -1
  32. package/prompts/zh/preset/procedure.md +1 -1
@@ -208,6 +208,11 @@ function shippedLanguages(shipped = shippedPromptsDirectory()) {
208
208
  return readdirSync(shipped, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
209
209
  }
210
210
  //#endregion
211
+ //#region src/host/errors.ts
212
+ function errorMessage(error) {
213
+ return error instanceof Error ? error.message : String(error);
214
+ }
215
+ //#endregion
211
216
  //#region src/host/validation.ts
212
217
  function formatIssue({ path, message }) {
213
218
  return path === "" ? message : `${path}: ${message}`;
@@ -343,11 +348,6 @@ var Reader = class Reader {
343
348
  }
344
349
  };
345
350
  //#endregion
346
- //#region src/host/errors.ts
347
- function errorMessage(error) {
348
- return error instanceof Error ? error.message : String(error);
349
- }
350
- //#endregion
351
351
  //#region src/host/read-document.ts
352
352
  /** Authored documents are short; a larger file is not one. */
353
353
  const MAX_DOCUMENT_BYTES = 1048576;
@@ -481,6 +481,6 @@ function plotReferenceProblems(plots, entities) {
481
481
  return plots.flatMap((plot) => plot.participants.filter((participant) => !known.has(participant)).map((participant) => `plot "${plot.id}" names unknown participant "${participant}"`));
482
482
  }
483
483
  //#endregion
484
- export { ReflectionRefusedError as C, WorldNotFoundError as E, InvalidWorldError as S, SessionNotFoundError as T, shippedLanguages as _, readDocument as a, AgentUnavailableError as b, formatIssue as c, PromptLibrary as d, copyWorldPrompts as f, promptProblem as g, listFiles as h, plotReferenceProblems as i, LANGUAGE_FOLDER as l, languageOf as m, loadPlots as n, errorMessage as o, inheritPrompts as p, parsePlotsFile as r, Reader as s, PLOTS_FILE_NAME as t, PROMPTS_FOLDER as u, shippedPromptsDirectory as v, SessionArchivedError as w, InvalidStartError as x, shippedText as y };
484
+ export { ReflectionRefusedError as C, WorldNotFoundError as E, InvalidWorldError as S, SessionNotFoundError as T, shippedLanguages as _, readDocument as a, AgentUnavailableError as b, errorMessage as c, PromptLibrary as d, copyWorldPrompts as f, promptProblem as g, listFiles as h, plotReferenceProblems as i, LANGUAGE_FOLDER as l, languageOf as m, loadPlots as n, Reader as o, inheritPrompts as p, parsePlotsFile as r, formatIssue as s, PLOTS_FILE_NAME as t, PROMPTS_FOLDER as u, shippedPromptsDirectory as v, SessionArchivedError as w, InvalidStartError as x, shippedText as y };
485
485
 
486
- //# sourceMappingURL=load-Clkl0T7C.js.map
486
+ //# sourceMappingURL=load-CVwJjIJ5.js.map
@@ -0,0 +1,619 @@
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";
6
+ import { join } from "node:path";
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
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
+ //#region src/host/import/lorebook.ts
29
+ const MAX_ENTRIES = 500;
30
+ const BATCH_CHARS = 6e3;
31
+ const BATCH_ENTRIES = 8;
32
+ /** The stand-in for the character a card's lorebook speaks of: a lorebook on its own belongs to no character. */
33
+ const CHARACTER_WORD = "the character";
34
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
35
+ const text = (value) => typeof value === "string" ? value.trim() : "";
36
+ 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. */
38
+ function bookOf(root) {
39
+ 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"];
41
+ return isObject(embedded) ? embedded : void 0;
42
+ }
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) {
48
+ let root;
49
+ try {
50
+ root = JSON.parse(file.toString("utf8").replace(/^/, ""));
51
+ } catch {
52
+ throw new ImportCardError("the file is not JSON: a lorebook is the .json file SillyTavern exports");
53
+ }
54
+ if (!isObject(root)) throw new ImportCardError("the file is not a lorebook: it must be a JSON object");
55
+ const book = bookOf(root);
56
+ 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"]) : [];
58
+ const entries = [];
59
+ for (const entry of raw) {
60
+ if (!isObject(entry)) continue;
61
+ if (entry["disable"] === true || entry["enabled"] === false) continue;
62
+ const content = cleanText(text(entry["content"]), CHARACTER_WORD);
63
+ if (content === "") continue;
64
+ const keys = [...strings(entry["keys"]), ...strings(entry["key"])];
65
+ entries.push({
66
+ ref: entries.length,
67
+ title: text(entry["comment"]) || text(entry["name"]),
68
+ keys,
69
+ text: content
70
+ });
71
+ }
72
+ if (entries.length === 0) throw new ImportCardError("the lorebook has no entries that are switched on and hold text");
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
+ return {
76
+ name: title === "" ? fileName.replace(/\.json$/i, "") : title,
77
+ entries
78
+ };
79
+ }
80
+ /** Where a piece of steering text goes: the prose prompts, and the prompts that tell the models how to run the game. */
81
+ const STEERING_TARGETS = {
82
+ style: "roleplay/style",
83
+ "character-style": "roleplay/character-style",
84
+ persona: "roleplay/persona",
85
+ "game-master": "roleplay/game-master",
86
+ "character-rules": "roleplay/character-rules"
87
+ };
88
+ const isSteeringTarget = (value) => Object.hasOwn(STEERING_TARGETS, value);
89
+ const RULES_TARGETS = ["game-master", "character-rules"];
90
+ /** Whether writing to the prompt changes how the models are told to run the game, not only how the story reads. */
91
+ const isRulesTarget = (target) => RULES_TARGETS.includes(target);
92
+ const DECISIONS_SCHEMA = {
93
+ type: "object",
94
+ properties: { entries: {
95
+ type: "array",
96
+ items: {
97
+ type: "object",
98
+ properties: {
99
+ ref: {
100
+ type: "integer",
101
+ description: "The number of the entry, as given."
102
+ },
103
+ role: {
104
+ type: "string",
105
+ enum: [
106
+ "knowledge",
107
+ "steering",
108
+ "skip"
109
+ ],
110
+ description: "knowledge: facts about the world. steering: instructions to the AI about how to write or run the story. skip: neither, or nothing usable."
111
+ },
112
+ title: {
113
+ type: "string",
114
+ description: "For knowledge: a short title (the entry's own when it is good). Empty otherwise."
115
+ },
116
+ kind: {
117
+ type: "string",
118
+ enum: [...LORE_KINDS],
119
+ description: "For knowledge: what kind of fact it is. Use other when none fits."
120
+ },
121
+ summary: {
122
+ type: "string",
123
+ description: "For knowledge: one sentence saying what the entry tells. Empty otherwise."
124
+ },
125
+ scope: {
126
+ type: "string",
127
+ enum: [...LORE_SCOPES],
128
+ description: "For knowledge: everyone, unless the entry itself clearly says that only some characters know it; then listed."
129
+ },
130
+ known_by: {
131
+ type: "array",
132
+ items: { type: "string" },
133
+ description: "When scope is listed: the characters that know it, as the entry names them. Empty otherwise."
134
+ },
135
+ target: {
136
+ type: "string",
137
+ enum: [...Object.keys(STEERING_TARGETS), ""],
138
+ description: "For steering: where it belongs. Empty otherwise."
139
+ },
140
+ guidance: {
141
+ type: "string",
142
+ description: "For steering: the instruction, as short direct guidance to the AI in the entry's own language, keeping everything it asks for. Empty otherwise."
143
+ }
144
+ },
145
+ required: [
146
+ "ref",
147
+ "role",
148
+ "title",
149
+ "kind",
150
+ "summary",
151
+ "scope",
152
+ "known_by",
153
+ "target",
154
+ "guidance"
155
+ ],
156
+ additionalProperties: false
157
+ }
158
+ } },
159
+ required: ["entries"],
160
+ additionalProperties: false
161
+ };
162
+ /** Groups entries into calls: a few at a time, within a budget of text, so that each answer is small and each entry gets attention. */
163
+ function batchesOf(entries) {
164
+ const batches = [];
165
+ let current = [];
166
+ let size = 0;
167
+ for (const entry of entries) {
168
+ if (current.length > 0 && (current.length >= BATCH_ENTRIES || size + entry.text.length > BATCH_CHARS)) {
169
+ batches.push(current);
170
+ current = [];
171
+ size = 0;
172
+ }
173
+ current.push(entry);
174
+ size += entry.text.length;
175
+ }
176
+ if (current.length > 0) batches.push(current);
177
+ return batches;
178
+ }
179
+ function problemOf(answer, batch) {
180
+ const given = answer.entries ?? [];
181
+ const wanted = new Set(batch.map((entry) => entry.ref));
182
+ const seen = /* @__PURE__ */ new Set();
183
+ for (const decision of given) {
184
+ if (!wanted.has(decision.ref)) return `entry ${decision.ref} was not given; the entries are ${[...wanted].join(", ")}`;
185
+ if (seen.has(decision.ref)) return `entry ${decision.ref} is decided twice`;
186
+ seen.add(decision.ref);
187
+ 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`;
189
+ 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`;
190
+ }
191
+ const missing = batch.filter((entry) => !seen.has(entry.ref)).map((entry) => entry.ref);
192
+ return missing.length === 0 ? void 0 : `decide every entry: ${missing.join(", ")} ${missing.length === 1 ? "is" : "are"} missing`;
193
+ }
194
+ const describe = (entry) => `Entry ${entry.ref}${entry.title === "" ? "" : ` “${entry.title}”`}${entry.keys.length === 0 ? "" : ` (triggers: ${entry.keys.join(", ")})`}:\n${entry.text}`;
195
+ /**
196
+ * Sorts the entries of a lorebook into what the world is (kept word for word as lorebook entries, common knowledge unless an entry clearly says otherwise)
197
+ * and what is told to the AI (kept as guidance for the prompts). Throws when the model never gives a usable answer, so that nothing half-made is written.
198
+ */
199
+ async function classifyEntries(ctx, book) {
200
+ const batches = batchesOf(book.entries);
201
+ ctx.say(`sorting ${book.entries.length} entries`);
202
+ const answers = await mapLimit(batches, ctx.concurrency, async (batch) => {
203
+ return await ctx.run({
204
+ persona: ctx.text("import/lorebook"),
205
+ prompt: `Lorebook: ${book.name}\n\n${batch.map(describe).join("\n\n---\n\n")}`,
206
+ result: DECISIONS_SCHEMA,
207
+ check: (value) => problemOf(value, batch)
208
+ });
209
+ });
210
+ const result = {
211
+ entries: [],
212
+ steering: {},
213
+ notes: []
214
+ };
215
+ const taken = /* @__PURE__ */ new Set();
216
+ for (const [index, batch] of batches.entries()) {
217
+ const decisions = new Map(answers[index].entries.map((decision) => [decision.ref, decision]));
218
+ for (const source of batch) {
219
+ const decision = decisions.get(source.ref);
220
+ const label = source.title === "" ? `entry ${source.ref}` : `“${source.title}”`;
221
+ if (decision.role === "skip") {
222
+ result.notes.push(`left out: ${label}`);
223
+ continue;
224
+ }
225
+ if (decision.role === "steering") {
226
+ const target = text(decision.target);
227
+ (result.steering[target] ??= []).push(withPlayer(text(decision.guidance)));
228
+ continue;
229
+ }
230
+ const title = (text(decision.title) || source.title).slice(0, 100);
231
+ const kind = LORE_KINDS.includes(decision.kind) ? decision.kind : "other";
232
+ const listed = decision.scope === "listed" && strings(decision.known_by).length > 0;
233
+ const also = source.keys.length === 0 ? "" : ` Also: ${source.keys.join(", ")}.`;
234
+ const parts = partsOf(withPlayer(source.text));
235
+ for (const [part, body] of parts.entries()) result.entries.push({
236
+ id: uniqueKey(slug(title, "entry"), taken),
237
+ title: parts.length === 1 ? title : `${title} (${part + 1})`,
238
+ kind,
239
+ scope: listed ? "listed" : "everyone",
240
+ knownBy: listed ? strings(decision.known_by) : [],
241
+ summary: `${text(decision.summary)}${part === 0 ? also : ""}`.trim(),
242
+ body,
243
+ related: []
244
+ });
245
+ }
246
+ }
247
+ return result;
248
+ }
249
+ //#endregion
250
+ //#region src/host/authoring/lorebook-author-tools.ts
251
+ const LOREBOOK_MUTATION_TOOLS = [
252
+ "write_lorebook_entry",
253
+ "delete_lorebook_entry",
254
+ "write_lorebook_info",
255
+ "import_lorebook",
256
+ "apply_steering"
257
+ ];
258
+ const LOREBOOK_IMPORT_TOOL = "import_lorebook";
259
+ const STEERING_TOOL = "apply_steering";
260
+ const LOREBOOK_UPLOAD = `${IMPORT_FOLDER}/lorebook.json`;
261
+ const STEERING_FILE = "steering.json";
262
+ /** The command that has a lorebook's authoring chat turn an uploaded SillyTavern lorebook into entries. */
263
+ const lorebookImportMessage = () => `Turn the SillyTavern lorebook I uploaded into this lorebook: call ${LOREBOOK_IMPORT_TOOL} with file ${LOREBOOK_UPLOAD}.`;
264
+ const output = (value) => [{
265
+ type: "text",
266
+ text: JSON.stringify(value, null, 2)
267
+ }];
268
+ const jsonOutput = {
269
+ schema: { type: "json" },
270
+ render: (_args, value) => output(value)
271
+ };
272
+ const json = (value) => JSON.parse(JSON.stringify(value));
273
+ /** The ids of the prompts waiting guidance would be written into, and whether any of them holds rules of the game. */
274
+ function pendingTargets(directory) {
275
+ const file = join(directory, IMPORT_FOLDER, STEERING_FILE);
276
+ if (!existsSync(file)) return {
277
+ ids: [],
278
+ rules: false
279
+ };
280
+ const pending = JSON.parse(readFileSync(file, "utf8"));
281
+ const ids = Object.keys(pending.guidance);
282
+ return {
283
+ ids,
284
+ rules: ids.some((id) => ![
285
+ "roleplay/persona",
286
+ "roleplay/style",
287
+ "roleplay/character-style"
288
+ ].includes(id))
289
+ };
290
+ }
291
+ /** Resolves every call from its lorebook authoring chat, so a tool can only reach the lorebook the chat is about. */
292
+ var LorebookReader = class {
293
+ root;
294
+ constructor(root) {
295
+ this.root = root;
296
+ }
297
+ directory(exec) {
298
+ const chat = exec.agent?.session.id;
299
+ const name = chat === void 0 ? void 0 : lorebookOfChat(chat);
300
+ if (name === void 0) throw new Error("this tool is available only in a lorebook authoring chat");
301
+ const directory = lorebookDirectory(this.root(), name);
302
+ if (!existsSync(directory)) throw new Error(`the lorebook "${name}" no longer exists`);
303
+ return {
304
+ name,
305
+ directory
306
+ };
307
+ }
308
+ get library() {
309
+ return this.root();
310
+ }
311
+ };
312
+ const entryParameters = { id: {
313
+ type: "string",
314
+ required: true,
315
+ description: "The entry's id: letters, digits, \"-\" and \"_\" (also used as its folder name)."
316
+ } };
317
+ /** Read and write the entries and the information of the lorebook the chat is about; the files are those a story start copies, so they are checked as it checks them. */
318
+ function lorebookAuthorTools(reader, settings, prompting, shipped = shippedPromptsDirectory()) {
319
+ return [
320
+ defineTool({
321
+ name: "read_lorebook_info",
322
+ description: "Read the lorebook's title, description, how many entries it has, how many everyone knows, and any problems it has.",
323
+ parameters: {},
324
+ output: jsonOutput,
325
+ isConcurrencySafe: () => true,
326
+ async execute(_args, exec) {
327
+ const { name, directory } = reader.directory(exec);
328
+ return json({
329
+ ...(await readLorebook$1(directory, name)).summary,
330
+ waitingGuidance: pendingTargets(directory).ids
331
+ });
332
+ }
333
+ }),
334
+ defineTool({
335
+ name: "list_lorebook_entries",
336
+ description: "List the entries of the lorebook with their kind, who knows them (scope) and summary, without the full text.",
337
+ parameters: {},
338
+ output: jsonOutput,
339
+ isConcurrencySafe: () => true,
340
+ async execute(_args, exec) {
341
+ const { name, directory } = reader.directory(exec);
342
+ return json(entriesOf(await readLorebook$1(directory, name)).map(({ body, ...rest }) => ({
343
+ ...rest,
344
+ characters: body.length
345
+ })));
346
+ }
347
+ }),
348
+ defineTool({
349
+ name: "read_lorebook_entry",
350
+ description: "Read one entry of the lorebook in full.",
351
+ parameters: entryParameters,
352
+ output: jsonOutput,
353
+ isConcurrencySafe: () => true,
354
+ async execute(args, exec) {
355
+ const { name, directory } = reader.directory(exec);
356
+ const found = entriesOf(await readLorebook$1(directory, name)).find((entry) => entry.id === args.id);
357
+ if (found === void 0) throw new Error(`the lorebook has no entry "${args.id}"`);
358
+ return json(found);
359
+ }
360
+ }),
361
+ defineTool({
362
+ name: "write_lorebook_entry",
363
+ description: "Create or replace an entry: a fact of the world, written as reference prose that keeps every detail. scope is \"everyone\" (common knowledge, which is the default and what a lorebook is for) or \"listed\", which only the characters in known_by know (by name, as they are called in the worlds it is used in; the game master always reads everything). Give the whole entry. Requires user approval.",
364
+ parameters: {
365
+ ...entryParameters,
366
+ title: {
367
+ type: "string",
368
+ required: true,
369
+ description: "A short title."
370
+ },
371
+ kind: {
372
+ type: "string",
373
+ required: true,
374
+ enum: [...LORE_KINDS],
375
+ description: "What kind of fact it is; other when none fits."
376
+ },
377
+ scope: {
378
+ type: "string",
379
+ required: true,
380
+ enum: [...LORE_SCOPES]
381
+ },
382
+ known_by: {
383
+ type: "array",
384
+ items: { type: "string" },
385
+ description: "For a listed entry: who knows it."
386
+ },
387
+ summary: {
388
+ type: "string",
389
+ description: "One sentence saying what the entry tells."
390
+ },
391
+ body: {
392
+ type: "string",
393
+ required: true,
394
+ description: "The entry's text."
395
+ },
396
+ related: {
397
+ type: "array",
398
+ items: { type: "string" },
399
+ description: "Ids of other entries of this book it goes with."
400
+ }
401
+ },
402
+ output: jsonOutput,
403
+ async execute(args, exec) {
404
+ const { name } = reader.directory(exec);
405
+ const entry = {
406
+ id: args.id,
407
+ title: args.title,
408
+ kind: args.kind,
409
+ scope: args.scope,
410
+ knownBy: args.known_by ?? [],
411
+ summary: args.summary ?? "",
412
+ body: args.body,
413
+ related: args.related ?? []
414
+ };
415
+ const book = await writeLorebookEntry(reader.library, name, entry);
416
+ return json({
417
+ action: "written",
418
+ id: args.id,
419
+ entries: book.summary.entries,
420
+ problems: book.summary.problems
421
+ });
422
+ }
423
+ }),
424
+ defineTool({
425
+ name: "delete_lorebook_entry",
426
+ description: "Remove an entry; it is moved into the lorebook's .trash. Refused while another entry relates to it. Requires user approval.",
427
+ parameters: entryParameters,
428
+ output: jsonOutput,
429
+ async execute(args, exec) {
430
+ const { name } = reader.directory(exec);
431
+ return json({
432
+ action: "deleted",
433
+ id: args.id,
434
+ entries: (await deleteLorebookEntry(reader.library, name, args.id)).summary.entries
435
+ });
436
+ }
437
+ }),
438
+ defineTool({
439
+ name: "write_lorebook_info",
440
+ description: "Change the lorebook's title and description (up to 300 characters each). Give only what changes. Requires user approval.",
441
+ parameters: {
442
+ title: {
443
+ type: "string",
444
+ description: "A short name to show; empty to clear."
445
+ },
446
+ description: {
447
+ type: "string",
448
+ description: "What the lorebook is about; empty to clear."
449
+ }
450
+ },
451
+ output: jsonOutput,
452
+ async execute(args, exec) {
453
+ const { name } = reader.directory(exec);
454
+ return json({
455
+ action: "written",
456
+ summary: (await updateLorebookInfo(reader.library, name, {
457
+ ...args.title === void 0 ? {} : { title: args.title },
458
+ ...args.description === void 0 ? {} : { description: args.description }
459
+ })).summary
460
+ });
461
+ }
462
+ }),
463
+ defineTool({
464
+ name: "read_waiting_guidance",
465
+ description: "Read the instructions to the AI that the import found in the uploaded lorebook and has not yet put into a preset, by the prompt they would be added to.",
466
+ parameters: {},
467
+ output: jsonOutput,
468
+ isConcurrencySafe: () => true,
469
+ async execute(_args, exec) {
470
+ const { directory } = reader.directory(exec);
471
+ const file = join(directory, IMPORT_FOLDER, STEERING_FILE);
472
+ return json(existsSync(file) ? JSON.parse(await readFile(file, "utf8")) : { guidance: {} });
473
+ }
474
+ }),
475
+ defineTool({
476
+ name: LOREBOOK_IMPORT_TOOL,
477
+ description: `Turn the SillyTavern lorebook the person uploaded (${LOREBOOK_UPLOAD}) into entries of this lorebook. Facts of the world are kept word for word as entries that everyone in a story knows, unless an entry clearly says only some characters know it. Instructions to the AI are not facts: they are kept aside, and ${STEERING_TOOL} puts them into a preset. Takes a few minutes. The person is asked first unless the lorebook is still empty.`,
478
+ parameters: { file: {
479
+ type: "string",
480
+ required: true,
481
+ description: `The uploaded lorebook: ${LOREBOOK_UPLOAD}.`
482
+ } },
483
+ output: jsonOutput,
484
+ isConcurrencySafe: () => false,
485
+ async execute(args, exec) {
486
+ if (args.file.trim() !== LOREBOOK_UPLOAD) throw new Error(`the uploaded lorebook is ${LOREBOOK_UPLOAD}`);
487
+ const { name, directory } = reader.directory(exec);
488
+ const uploaded = readLorebook(await readFile(join(directory, IMPORT_FOLDER, "lorebook.json")).catch(() => {
489
+ throw new Error("no lorebook was uploaded here");
490
+ }), name);
491
+ const language = prompting.languages().get(`lorebook:${name}`);
492
+ const text = (id, variables) => prompting.prompts().text(id, language, variables);
493
+ const made = await classifyEntries(contextOf(exec, settings(), text), uploaded);
494
+ const taken = new Set((await loadLorebook(reader.library, name)).entries.map((entry) => entry.id));
495
+ for (const entry of made.entries) {
496
+ let id = entry.id;
497
+ for (let n = 2; taken.has(id); n += 1) id = `${entry.id}-${n}`;
498
+ taken.add(id);
499
+ await writeLorebookEntry(reader.library, name, {
500
+ ...entry,
501
+ id
502
+ });
503
+ }
504
+ const guidance = Object.fromEntries(Object.entries(made.steering).map(([target, lines]) => [STEERING_TARGETS[target], lines]));
505
+ if (Object.keys(guidance).length > 0) await writeFile(join(directory, IMPORT_FOLDER, STEERING_FILE), JSON.stringify({
506
+ source: uploaded.name,
507
+ guidance
508
+ }, null, 2));
509
+ await rm(join(directory, IMPORT_FOLDER, "lorebook.json"), { force: true });
510
+ const waiting = Object.keys(guidance);
511
+ return json({
512
+ entries: made.entries.length,
513
+ everyone: made.entries.filter((entry) => entry.scope === "everyone").length,
514
+ listed: made.entries.filter((entry) => entry.scope === "listed").map((entry) => ({
515
+ title: entry.title,
516
+ knownBy: entry.knownBy
517
+ })),
518
+ notes: made.notes,
519
+ waitingGuidance: waiting,
520
+ rulesPrompts: waiting.filter((id) => isRulesTarget(Object.entries(STEERING_TARGETS).find(([, value]) => value === id)[0])),
521
+ next: waiting.length === 0 ? "Tell the person how many entries were made, what was left out, and any entry that is known only to some characters." : `Tell the person how many entries were made and what was left out. ${waiting.length} prompt(s) have instructions waiting (${waiting.join(", ")}): say what they are about (read_waiting_guidance), warn the person that any prompt other than roleplay/persona, roleplay/style and roleplay/character-style holds rules of the game, and ask whether to call ${STEERING_TOOL} to put them into a new preset.`
522
+ });
523
+ }
524
+ }),
525
+ defineTool({
526
+ name: STEERING_TOOL,
527
+ description: "Make a new preset in the preset library from the instructions the import set aside: each prompt keeps its shipped text and the instructions follow it, in every language. Prompts other than the three prose ones hold rules of the game, and the person is warned. Requires user approval.",
528
+ parameters: {
529
+ preset: {
530
+ type: "string",
531
+ description: "The preset's name (letters, digits, \"-\" and \"_\"); the lorebook's own name when left out."
532
+ },
533
+ title: {
534
+ type: "string",
535
+ description: "The preset's title."
536
+ }
537
+ },
538
+ output: jsonOutput,
539
+ isConcurrencySafe: () => false,
540
+ async execute(args, exec) {
541
+ const { name, directory } = reader.directory(exec);
542
+ const file = join(directory, IMPORT_FOLDER, STEERING_FILE);
543
+ if (!existsSync(file)) throw new Error("there is no guidance waiting");
544
+ const pending = JSON.parse(await readFile(file, "utf8"));
545
+ const made = await createPresetFromGuidance(reader.library, {
546
+ name: args.preset?.trim() || name,
547
+ title: args.title ?? pending.source
548
+ }, pending.guidance, shipped);
549
+ await rm(file, { force: true });
550
+ return json({
551
+ action: "preset made",
552
+ preset: made.summary.name,
553
+ prompts: made.summary.prompts,
554
+ rules: made.summary.rules,
555
+ next: "Tell the person the preset name and that they can choose it when starting a story, or set it as a world's suggested preset."
556
+ });
557
+ }
558
+ })
559
+ ];
560
+ }
561
+ /** Every change to a lorebook is put to the person; the first import into an empty one only fills it, and a preset made of guidance warns when it touches rules of the game. */
562
+ async function lorebookApproval(exec, next, state) {
563
+ if (!LOREBOOK_MUTATION_TOOLS.includes(exec.name) || exec.agent === void 0 || lorebookOfChat(exec.agent.session.id) === void 0) return await next();
564
+ const args = exec.arguments;
565
+ const chat = exec.agent.session.id;
566
+ if (exec.name === "import_lorebook") {
567
+ if (!state.carries(chat)) return await next();
568
+ return {
569
+ kind: "ask",
570
+ reason: "add the entries of the uploaded lorebook to this lorebook",
571
+ displayReason: {
572
+ en: "Add the entries of the uploaded lorebook to this lorebook?",
573
+ zh: "把上传的世界书中的条目加入此世界书?"
574
+ }
575
+ };
576
+ }
577
+ if (exec.name === "apply_steering") {
578
+ const { ids, rules } = state.waiting(chat);
579
+ const list = ids.join(", ");
580
+ if (rules) return {
581
+ kind: "ask",
582
+ reason: `make a preset from the instructions of the lorebook, including rules prompts (${list})`,
583
+ displayReason: {
584
+ en: `WARNING: make a preset that adds the lorebook's instructions to ${list}? Some of these prompts hold rules of the game, not only prose; a wrong instruction can break how the story runs.`,
585
+ zh: `警告:创建一个预设,把世界书中的指令加入 ${list}?其中一些提示词属于游戏规则,而不只是文风;错误的指令可能影响故事的运行。`
586
+ }
587
+ };
588
+ return {
589
+ kind: "ask",
590
+ reason: `make a preset from the instructions of the lorebook (${list})`,
591
+ displayReason: {
592
+ en: `Make a preset that adds the lorebook's instructions to ${list}?`,
593
+ zh: `创建一个预设,把世界书中的指令加入 ${list}?`
594
+ }
595
+ };
596
+ }
597
+ if (exec.name === "write_lorebook_info") return {
598
+ kind: "ask",
599
+ reason: "change the lorebook's title or description",
600
+ displayReason: {
601
+ en: "Change the lorebook's title or description?",
602
+ zh: "修改世界书的标题或描述?"
603
+ }
604
+ };
605
+ const target = `entry “${String(args["id"])}”`;
606
+ const remove = exec.name.startsWith("delete");
607
+ return {
608
+ kind: "ask",
609
+ reason: `${remove ? "delete" : "write"} lorebook ${target}`,
610
+ displayReason: {
611
+ en: `${remove ? "Delete" : "Write"} ${target} in the lorebook?`,
612
+ zh: `${remove ? "删除" : "写入"}世界书中的${target}?`
613
+ }
614
+ };
615
+ }
616
+ //#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 };
618
+
619
+ //# sourceMappingURL=lorebook-author-tools-Bj31z1cu.js.map