@dsh-agentic-roleplay/core 0.3.6 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/lib/{tools-Dy1fgP6B.js → authoring-tools-C_8ClUkP.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 +3714 -2264
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +1 -1
  7. package/lib/doctor.js +2 -4
  8. package/lib/{gallery-DIEgETzU.js → gallery-CDYKJf_O.js} +2 -2
  9. package/lib/{generator-DJ48HxPI.js → generator-BR1ugzln.js} +2 -2
  10. package/lib/{deliver-BBgciEEK.js → hooks-B2EhBS_-.js} +1884 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +846 -254
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/{lorebook-author-tools-Bj31z1cu.js → lorebook-author-tools-C-o0t4dL.js} +118 -43
  15. package/lib/lorebook-authoring.js +5 -3
  16. package/lib/{settings-CA6icLL_.js → narration-BT9uvQry.js} +145 -2
  17. package/lib/orchestration.js +34 -21
  18. package/lib/{pack-jail-2XztyYAX.js → pack-jail-soI-In96.js} +170 -13
  19. package/lib/{packs-xHRCcGdb.js → packs-CJPSe5LI.js} +7 -4
  20. package/lib/{presenter-agent-DnNEG_Mn.js → presenter-agent-Gu34bZwd.js} +6 -6
  21. package/lib/preset-3zn8xme7.js +242 -0
  22. package/lib/{preset-author-tools-BxycmoAr.js → preset-author-tools-C-X8G40s.js} +7 -7
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-gkBWAiVb.js → presets-C3mhqqfz.js} +9 -26
  25. package/lib/{reflection-q0UpwXlx.js → reflection-Btsj0ZLh.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/world/procedure.md +1 -1
  36. package/prompts/zh/import/lorebook.md +2 -1
  37. package/prompts/zh/import/style.md +1 -0
  38. package/prompts/zh/lorebook/procedure.md +1 -1
  39. package/prompts/zh/preset/procedure.md +1 -1
  40. package/prompts/zh/roleplay/character-lookup.md +1 -0
  41. package/prompts/zh/roleplay/game-master.md +1 -1
  42. package/prompts/zh/world/procedure.md +1 -1
  43. package/lib/hooks-DkwFGtNH.js +0 -1060
  44. package/lib/language-BgyxtB2h.js +0 -38
  45. package/lib/load-CVwJjIJ5.js +0 -486
  46. package/lib/narration-DK2kiIjE.js +0 -141
  47. package/lib/preset-D0FMSeZ9.js +0 -59
@@ -1,14 +1,15 @@
1
- import { a as isPresetName, b as INTENT_STATUSES, m as PROSE_PROMPTS, x as INTENT_TYPES, y as INTENT_HORIZONS } from "./presets-gkBWAiVb.js";
2
- import { c as VARIABLE_SUBJECTS, i as parseSwitchboard, l as VARIABLE_VISIBILITIES, s as VARIABLE_KINDS } from "./settings-CA6icLL_.js";
3
- import { S as InvalidWorldError, _ as shippedLanguages, a as readDocument, c as errorMessage, g as promptProblem, i as plotReferenceProblems, n as loadPlots, o as Reader, s as formatIssue, u as PROMPTS_FOLDER } from "./load-CVwJjIJ5.js";
4
- import { a as runChild } from "./child-CFjnaTZt.js";
5
- import { b as slug, c as referenceImagePath, d as MEDIA_TYPES, h as writeImageFileMetadata, n as imageExtensionOf, t as addToLibrary, v as mapLimit, x as uniqueKey, y as norm } from "./library-9JB9zw5a.js";
1
+ import { a as isPresetName, b as INTENT_STATUSES, m as PROSE_PROMPTS, x as INTENT_TYPES, y as INTENT_HORIZONS } from "./presets-C3mhqqfz.js";
2
+ import { _ as VARIABLE_VISIBILITIES, f as parseSwitchboard, g as VARIABLE_SUBJECTS, h as VARIABLE_KINDS } from "./narration-BT9uvQry.js";
3
+ import { B as readDocument, G as PROMPTS_FOLDER, H as formatIssue, L as loadPlots, Q as shippedLanguages, U as errorMessage, V as Reader, Z as promptProblem, a as externalWithheld, nt as InvalidWorldError, r as externalGiven, t as externalToolLimit, z as plotReferenceProblems } from "./hooks-B2EhBS_-.js";
4
+ import { a as runChild, h as trimCharacters, s as parseSampling } from "./child-DsixtqTw.js";
5
+ import { b as slug, c as referenceImagePath, d as MEDIA_TYPES, h as writeImageFileMetadata, n as imageExtensionOf, t as addToLibrary, v as mapLimit, x as uniqueKey, y as norm } from "./library-COIktKBa.js";
6
6
  import { dirname, join } from "node:path";
7
7
  import { existsSync, readFileSync } from "node:fs";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
10
10
  import { inflateSync } from "node:zlib";
11
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
12
+ import { Service } from "@deepseek-ai/cordis";
12
13
  import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
13
14
  import { MAX_ROUTINE_WINDOWS, MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, valueIssue, writeCalendar } from "@dsh-agentic-roleplay/state";
14
15
  import { lookup } from "node:dns";
@@ -250,7 +251,7 @@ function urlsOf(value) {
250
251
  const visit = (node, depth) => {
251
252
  if (depth > 32) return;
252
253
  if (typeof node === "string") for (const match of node.matchAll(URL_PATTERN)) {
253
- const url = match[0].replace(/[.,;:!?*_~]+$/, "");
254
+ const url = trimCharacters(match[0], ".,;:!?*_~", "end");
254
255
  if (!url.includes("$") && url.length <= 2e3) found.add(url);
255
256
  }
256
257
  else if (Array.isArray(node)) for (const entry of node) visit(entry, depth + 1);
@@ -335,10 +336,16 @@ const isPng = (file) => file.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNAT
335
336
  const IMPORT_COMMAND = "/import-st";
336
337
  /** The command in a message, with the card it names, or nothing when the message is not the command. */
337
338
  function parseImportCommand(text) {
338
- const match = /^\s*\/import-st(?=\s|$)\s*(\S*)\s*([\s\S]*)$/i.exec(text);
339
- return match === null ? void 0 : {
340
- card: match[1] ?? "",
341
- request: (match[2] ?? "").trim()
339
+ const value = text.trimStart();
340
+ if (value.slice(0, 10).toLowerCase() !== "/import-st" || value.length > 10 && !/\s/u.test(value[10])) return void 0;
341
+ const body = value.slice(10).trimStart();
342
+ const boundary = body.search(/\s/u);
343
+ return boundary < 0 ? {
344
+ card: body,
345
+ request: ""
346
+ } : {
347
+ card: body.slice(0, boundary),
348
+ request: body.slice(boundary).trim()
342
349
  };
343
350
  }
344
351
  //#endregion
@@ -704,6 +711,8 @@ function parseLoreEdit(value) {
704
711
  for (const key of Object.keys(input)) if (![
705
712
  "title",
706
713
  "kind",
714
+ "scope",
715
+ "knownBy",
707
716
  "summary",
708
717
  "body",
709
718
  "startsAt",
@@ -724,6 +733,16 @@ function parseLoreEdit(value) {
724
733
  if (typeof input["kind"] !== "string" || !LORE_KINDS.includes(input["kind"])) problems.push(`kind must be one of: ${LORE_KINDS.join(", ")}`);
725
734
  else edit.kind = input["kind"];
726
735
  }
736
+ if ("scope" in input) {
737
+ if (typeof input["scope"] !== "string" || !LORE_SCOPES.includes(input["scope"])) problems.push(`scope must be one of: ${LORE_SCOPES.join(", ")}`);
738
+ else edit.scope = input["scope"];
739
+ }
740
+ if ("knownBy" in input) {
741
+ const found = input["knownBy"];
742
+ if (!Array.isArray(found) || !found.every((entry) => typeof entry === "string" && entry.trim() !== "" && entry.length <= TEXT_LIMIT)) problems.push("knownBy must be a list of names");
743
+ else edit.knownBy = found.map((entry) => entry.trim());
744
+ }
745
+ if (edit.scope === "everyone" && (edit.knownBy?.length ?? 0) > 0) problems.push("an entry everyone knows has no list of who knows it");
727
746
  for (const key of ["startsAt", "endsAt"]) if (key in input) {
728
747
  const found = input[key];
729
748
  if (found !== null && (typeof found !== "number" || !Number.isFinite(found))) problems.push(`${key} must be a timestamp or null`);
@@ -1179,6 +1198,28 @@ function entryProblem(entry) {
1179
1198
  }), entry.id);
1180
1199
  return parsed.ok ? void 0 : parsed.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ");
1181
1200
  }
1201
+ /**
1202
+ * Creates several new entries of a lorebook at once, each checked as `writeLorebookEntry` checks one; none is written when any is not acceptable.
1203
+ * @throws {Error} when the lorebook does not exist, an id is taken or an entry is not acceptable, or the book would have more entries than a world may.
1204
+ */
1205
+ async function addLorebookEntries(root, name, entries) {
1206
+ const directory = lorebookDirectory(root, name);
1207
+ if (!existsSync(directory)) throw new Error(`there is no lorebook "${name}"`);
1208
+ const book = await readLorebook(directory, name);
1209
+ if (book.entries.length + entries.length > 500) throw new Error(`a lorebook has at most 500 entries`);
1210
+ const ids = new Set(book.entries.map((entry) => entry.id));
1211
+ for (const entry of entries) {
1212
+ const problem = entryProblem(entry);
1213
+ if (problem !== void 0) throw new Error(`entry "${entry.title}": ${problem}`);
1214
+ if (ids.has(entry.id)) throw new Error(`there is already an entry "${entry.id}"`);
1215
+ ids.add(entry.id);
1216
+ }
1217
+ for (const entry of entries) await writeAtomic(join(directory, LORE_DIR, entry.id, LORE_FILE_NAME), entryFile({
1218
+ ...entry,
1219
+ title: entry.title.trim()
1220
+ }));
1221
+ return await readLorebook(directory, name);
1222
+ }
1182
1223
  /** Creates or replaces one entry. @throws {Error} when the lorebook does not exist, the entry is not acceptable or the book would have more entries than a world may. */
1183
1224
  async function writeLorebookEntry(root, name, entry) {
1184
1225
  const directory = lorebookDirectory(root, name);
@@ -1241,7 +1282,7 @@ function parseWorldInfoEdit(value) {
1241
1282
  const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1242
1283
  if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
1243
1284
  const edit = {};
1244
- for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "tools") problems.push(`there is no field "${key}"`);
1285
+ for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "tools" && key !== "sampling") problems.push(`there is no field "${key}"`);
1245
1286
  for (const key of TEXT_FIELDS) {
1246
1287
  if (input[key] === void 0) continue;
1247
1288
  if (typeof input[key] === "string") edit[key] = input[key].trim();
@@ -1272,6 +1313,7 @@ function parseWorldInfoEdit(value) {
1272
1313
  if (typeof board === "string") problems.push(board);
1273
1314
  else edit["tools"] = board;
1274
1315
  }
1316
+ if (input["sampling"] !== void 0) edit["sampling"] = parseSampling(input["sampling"], "sampling", problems);
1275
1317
  if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
1276
1318
  if (edit["name"] === "") problems.push("the world needs a name");
1277
1319
  if (typeof edit["name"] === "string" && edit["name"].length > 200) problems.push(`the name is longer than 200 characters`);
@@ -1315,6 +1357,13 @@ function readTools(reader) {
1315
1357
  }
1316
1358
  return Object.keys(board).length === 0 ? void 0 : board;
1317
1359
  }
1360
+ /** `sampling` is an object of the controls a story's requests may carry (see `StorySampling`). */
1361
+ function readSampling(reader) {
1362
+ const problems = [];
1363
+ const sampling = parseSampling(reader.raw("sampling"), "sampling", problems);
1364
+ for (const problem of problems) reader.fail("sampling", problem.replace(/^sampling\.?/, ""));
1365
+ return Object.keys(sampling).length === 0 ? void 0 : sampling;
1366
+ }
1318
1367
  /** `rules` is one rule as text, or a list of them; blank ones are left out. */
1319
1368
  function readRules(reader) {
1320
1369
  const value = reader.raw("rules");
@@ -1411,6 +1460,7 @@ function parseWorldFile(text) {
1411
1460
  const tools = readTools(reader);
1412
1461
  const alternateOpenings = readAlternateOpenings(reader);
1413
1462
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
1463
+ const sampling = readSampling(reader);
1414
1464
  const preset = reader.string("preset")?.trim() || void 0;
1415
1465
  if (preset !== void 0 && !isPresetName(preset)) reader.fail("preset", "must be the name of a preset: letters, digits, \"-\" and \"_\"");
1416
1466
  const lorebooks = reader.strings("lorebooks").map((entry) => entry.trim()).filter((entry) => entry !== "");
@@ -1436,6 +1486,7 @@ function parseWorldFile(text) {
1436
1486
  ...tools === void 0 ? {} : { tools },
1437
1487
  ...alternateOpenings === void 0 ? {} : { alternateOpenings },
1438
1488
  ...narrationVoice === void 0 ? {} : { narrationVoice },
1489
+ ...sampling === void 0 ? {} : { sampling },
1439
1490
  ...preset === void 0 ? {} : { preset },
1440
1491
  ...lorebooks.length === 0 ? {} : { lorebooks: [...new Set(lorebooks)] }
1441
1492
  }
@@ -2379,7 +2430,7 @@ const MAX_ITEM_CHARS = 5e3;
2379
2430
  const PLAYER_MARKER = "[PLAYER]";
2380
2431
  /** Macros and markup of the tool that wrote the card, taken out of text a model reads: the card's own name stands for `{{char}}`; the player becomes the marker `[PLAYER]`. */
2381
2432
  function cleanText(text, cardName) {
2382
- return text.replace(/\r\n?/g, "\n").replace(/<!--[\s\S]*?-->/g, "").replace(/\{\{\s*\/\/[\s\S]*?\}\}/g, "").replace(/\{\{\s*char\s*\}\}|<char>|<bot>/gi, cardName).replace(/\{\{\s*user\s*\}\}|<user>/gi, PLAYER_MARKER).replace(/^\s*<START>\s*$/gim, "").replace(/\n{3,}/g, "\n\n").trim();
2433
+ return text.replace(/\r\n?/g, "\n").replace(/<!--[\s\S]*?-->/g, "").replace(/\{\{\s*\/\/[\s\S]*?\}\}/g, "").replace(/\{\{\s*char\s*\}\}|<char>|<bot>/gi, cardName).replace(/\{\{\s*user\s*\}\}|<user>/gi, PLAYER_MARKER).split("\n").filter((line) => line.trim().toUpperCase() !== "<START>").join("\n").replace(/\n{3,}/g, "\n\n").trim();
2383
2434
  }
2384
2435
  /** Cuts a text into parts of at most `max` characters, at the end of a paragraph, or of a line, or anywhere when there is no choice. */
2385
2436
  function partsOf(text, max = MAX_ITEM_CHARS) {
@@ -3579,12 +3630,18 @@ const STYLE_SCHEMA = {
3579
3630
  type: "array",
3580
3631
  items: { type: "string" },
3581
3632
  description: "What the instructions contained that is not prose or behaviour guidance (rules of the game, formats, panels, scripts), one short phrase each."
3633
+ },
3634
+ persona_names: {
3635
+ type: "array",
3636
+ items: { type: "string" },
3637
+ description: "Every name the instructions give to the AI itself (a writer, narrator or assistant persona), exactly as written; empty when it has none. These names must not appear in narration or characters."
3582
3638
  }
3583
3639
  },
3584
3640
  required: [
3585
3641
  "narration",
3586
3642
  "characters",
3587
- "left_out"
3643
+ "left_out",
3644
+ "persona_names"
3588
3645
  ]
3589
3646
  };
3590
3647
  const MAX_STYLE_CHARS = 2e3;
@@ -3594,7 +3651,9 @@ function instructionPieces(card, items, classified) {
3594
3651
  const pieces = items.filter((item) => classified[item.id]?.roles[0] === "instruction").map((item) => item.text);
3595
3652
  return [...fields, ...pieces];
3596
3653
  }
3597
- function styleProblem(id, value) {
3654
+ function styleProblem(id, value, personas = []) {
3655
+ const named = personas.find((name) => name.trim() !== "" && value.toLowerCase().includes(name.trim().toLowerCase()));
3656
+ if (named !== void 0) return `${id} uses the persona name "${named}"; say "the character" or "the narrator" instead`;
3598
3657
  if (value.length > MAX_STYLE_CHARS) return `${id} is ${value.length} characters long; keep it to ${MAX_STYLE_CHARS}`;
3599
3658
  return value === "" ? void 0 : promptProblem("en", id, value);
3600
3659
  }
@@ -3615,7 +3674,7 @@ async function extractStyleFrom(ctx, name, pieces) {
3615
3674
  persona: ctx.text("import/style", { rules: ctx.text("import/common-rules") }),
3616
3675
  prompt,
3617
3676
  result: STYLE_SCHEMA,
3618
- check: (value) => styleProblem("roleplay/style", text(value.narration)) ?? styleProblem("roleplay/character-style", text(value.characters))
3677
+ check: (value) => styleProblem("roleplay/style", text(value.narration), list(value.persona_names)) ?? styleProblem("roleplay/character-style", text(value.characters), list(value.persona_names))
3619
3678
  });
3620
3679
  const prompts = [["roleplay/style", text(answer.narration)], ["roleplay/character-style", text(answer.characters)]].flatMap(([id, body]) => body === "" ? [] : [{
3621
3680
  id,
@@ -4423,7 +4482,8 @@ function loreProblems(lore, world) {
4423
4482
  ...entry.related.flatMap((id) => id === entry.id ? [`${entry.id}: related: lore cannot relate to itself`] : ids.lore.has(id) ? [] : [`${entry.id}: related: "${id}" is not lore of this world`])
4424
4483
  ]);
4425
4484
  }
4426
- function populateLore(session, definitions) {
4485
+ /** `turn` is when the characters that know an entry learned it: 0 at the start, the story's turn when a lorebook is added later. */
4486
+ function populateLore(session, definitions, turn = 0) {
4427
4487
  for (const entry of definitions) session.lore.add({
4428
4488
  sourceId: entry.id,
4429
4489
  title: entry.title,
@@ -4449,7 +4509,7 @@ function populateLore(session, definitions) {
4449
4509
  const lore = session.lore.getBySourceId(entry.id);
4450
4510
  for (const reference of entry.knownBy) {
4451
4511
  const knower = session.characters.getBySourceId(reference) ?? session.characters.findByName(reference)[0];
4452
- if (knower !== void 0) session.knowledge.learn(knower.id, "lore", lore.id, 0);
4512
+ if (knower !== void 0) session.knowledge.learn(knower.id, "lore", lore.id, turn);
4453
4513
  }
4454
4514
  }
4455
4515
  }
@@ -4477,10 +4537,11 @@ function populateVariables(session, defs, world) {
4477
4537
  give("world", 0, world.values);
4478
4538
  }
4479
4539
  /** What is wrong with the days characters are given, found before anything is created: places that are not in the world. */
4480
- function routineProblems(characters, locations, calendar = {
4481
- hemisphere: "north",
4482
- holidays: []
4483
- }) {
4540
+ function routineProblems(characters, locations, calendar) {
4541
+ calendar ??= {
4542
+ hemisphere: "north",
4543
+ holidays: []
4544
+ };
4484
4545
  const byId = new Map(locations.map((location) => [location.id, location]));
4485
4546
  const holidays = new Set(calendar.holidays.map((holiday) => holiday.id));
4486
4547
  return characters.flatMap((character) => (character.routine ?? []).flatMap((window, index) => {
@@ -5291,8 +5352,8 @@ function isPublicAddress(address) {
5291
5352
  if (family === 4) return !blocked.check(address, "ipv4");
5292
5353
  const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(new URL(`http://[${address}]/`).hostname.replace(/^\[|\]$/g, ""));
5293
5354
  if (mapped !== null) {
5294
- const high = parseInt(mapped[1], 16);
5295
- const low = parseInt(mapped[2], 16);
5355
+ const high = Number.parseInt(mapped[1], 16);
5356
+ const low = Number.parseInt(mapped[2], 16);
5296
5357
  return isPublicAddress(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`);
5297
5358
  }
5298
5359
  return !blocked.check(address, "ipv6");
@@ -5944,6 +6005,49 @@ function importHooks(ctx, worlds, prompting) {
5944
6005
  });
5945
6006
  }
5946
6007
  //#endregion
5947
- export { parseItemFile as $, parseDiceFile as A, parseFactionEdit as At, CHARACTERS_DIR as B, LORE_KINDS as Bt, populateTriggers as C, LORE_DIR as Ct, loadTriggers as D, subfolders as Dt, TRIGGERS_FILE_NAME as E, parseLoreFile as Et, loadLocations as F, IMPORT_COMMAND as Ft, withPlayer as G, extractStyleFrom as H, DICE_COMPARISONS as Ht, ITEMS_DIR as I, ImportCardError as It, parseVariablesFile as J, VARIABLES_FILE_NAME as K, loadItems as L, isPng as Lt, loadCalendar as M, parsePlaceEdit as Mt, parseCalendarFile as N, parseRelationEdit as Nt, DICE_FILE_NAME as O, InvalidEditProblems as Ot, LOCATIONS_DIR as P, parseThingEdit as Pt, ITEM_FILE_NAME as Q, FACTIONS_DIR as R, pictureOf as Rt, populateRoutines as S, writeLorebookEntry as St, routineProblems as T, LORE_FILE_NAME as Tt, cleanText as U, DICE_READINGS as Ut, loadCharacters as V, LORE_SCOPES as Vt, partsOf as W, DICE_RESULTS as Wt, LOCATION_FILE_NAME as X, variableProblems as Y, parseLocationFile as Z, populateFactions as _, loadLorebook as _t, authoredWorldOf as a, ImportNotFoundError as at, populateLocations as b, reserveLorebook as bt, markReady as c, WORLD_FILE_NAME as ct, loadValidatedWorld as d, createLorebook as dt, FACTION_FILE_NAME as et, knowsCharacter as f, deleteLorebook as ft, populateDice as g, listLorebooks as gt, populateClock as h, isLorebookName as ht, worldOf as i, IMPORT_FOLDER as it, CALENDAR_FILE_NAME as j, parseLoreEdit as jt, loadDice as k, parseCharacterEdit as kt, guardedLookup as l, parseWorldFile as lt, populateCharacters as m, entriesOf as mt, importHooks as n, CHARACTER_FILE_NAME as nt, authoringChatSessionId as o, ImportStore as ot, populateCalendar as p, deleteLorebookEntry as pt, loadVariables as q, importTools as r, parseCharacterFile as rt, isReviewing as s, parseChoices as st, contextOf as t, parseFactionFile as tt, vetUrl as u, parseWorldInfoEdit as ut, populateItems as v, lorebookDirectory as vt, populateVariables as w, loadLore as wt, populateLore as x, updateLorebookInfo as xt, populateKnowledge as y, readLorebook as yt, loadFactions as z, readCard as zt };
6008
+ //#region src/shared/import-selection.ts
6009
+ const MAX_PREVIEW_TEXT = 4e3;
6010
+ //#endregion
6011
+ //#region src/host/tools/authoring-tools.ts
6012
+ /** Which of the tools other plugins registered for everyone each assistant of the authoring chats was given in the settings; read afresh, so a change applies at its next step. */
6013
+ var AuthoringTools = class extends Service {
6014
+ board;
6015
+ constructor(ctx, board) {
6016
+ super(ctx, "roleplayAuthoringTools");
6017
+ this.board = board;
6018
+ }
6019
+ /** What the assistant is given: the tools it may call on top of its own. */
6020
+ given(registry, kind) {
6021
+ return externalGiven(registry, this.board(), kind);
6022
+ }
6023
+ /** What the assistant is not given and so does not see. */
6024
+ withheld(registry, kind) {
6025
+ return externalWithheld(registry, this.board(), kind);
6026
+ }
6027
+ };
6028
+ /**
6029
+ * Takes the tools of other plugins away from an assistant of an authoring chat unless the settings gave it that tool, before its first request and again
6030
+ * at every step (a server may connect later). Helpers the assistant starts are not touched: they have no tools but their own.
6031
+ */
6032
+ function limitAuthoringAgent(agent, kind, tools) {
6033
+ externalToolLimit(agent, tools.withheld(agent.ctx.tools, kind));
6034
+ }
6035
+ /** Installs the limit on the agents of the chats `kindOf` recognises, which a preset's listeners find among the agents of every chat of the preset and its helpers. */
6036
+ function limitAuthoringAgents(ctx, kindOf) {
6037
+ const apply = (agent) => {
6038
+ if (agent.session.header.origin === "subagent") return;
6039
+ const kind = kindOf(agent.session.id);
6040
+ if (kind !== void 0) limitAuthoringAgent(agent, kind, ctx.roleplayAuthoringTools);
6041
+ };
6042
+ ctx.on("agent/created", ({ agent }) => {
6043
+ apply(agent);
6044
+ });
6045
+ ctx.on("agent/pre-step", async (payload, next) => {
6046
+ apply(payload.agent);
6047
+ return await next();
6048
+ });
6049
+ }
6050
+ //#endregion
6051
+ export { LOCATION_FILE_NAME as $, loadTriggers as A, parseLoreFile as At, loadItems as B, ImportCardError as Bt, populateLocations as C, readLorebook as Ct, populateVariables as D, LORE_DIR as Dt, populateTriggers as E, writeLorebookEntry as Et, loadCalendar as F, parseLoreEdit as Ft, extractStyleFrom as G, LORE_SCOPES as Gt, loadFactions as H, pictureOf as Ht, parseCalendarFile as I, parsePlaceEdit as It, withPlayer as J, DICE_RESULTS as Jt, cleanText as K, DICE_COMPARISONS as Kt, LOCATIONS_DIR as L, parseRelationEdit as Lt, loadDice as M, InvalidEditProblems as Mt, parseDiceFile as N, parseCharacterEdit as Nt, routineProblems as O, loadLore as Ot, CALENDAR_FILE_NAME as P, parseFactionEdit as Pt, variableProblems as Q, loadLocations as R, parseThingEdit as Rt, populateKnowledge as S, lorebookDirectory as St, populateRoutines as T, updateLorebookInfo as Tt, CHARACTERS_DIR as U, readCard as Ut, FACTIONS_DIR as V, isPng as Vt, loadCharacters as W, LORE_KINDS as Wt, loadVariables as X, VARIABLES_FILE_NAME as Y, parseVariablesFile as Z, populateCharacters as _, deleteLorebookEntry as _t, importHooks as a, CHARACTER_FILE_NAME as at, populateFactions as b, listLorebooks as bt, authoredWorldOf as c, ImportNotFoundError as ct, markReady as d, WORLD_FILE_NAME as dt, parseLocationFile as et, guardedLookup as f, parseWorldFile as ft, populateCalendar as g, deleteLorebook as gt, knowsCharacter as h, createLorebook as ht, contextOf as i, parseFactionFile as it, DICE_FILE_NAME as j, subfolders as jt, TRIGGERS_FILE_NAME as k, LORE_FILE_NAME as kt, authoringChatSessionId as l, ImportStore as lt, loadValidatedWorld as m, addLorebookEntries as mt, limitAuthoringAgents as n, parseItemFile as nt, importTools as o, parseCharacterFile as ot, vetUrl as p, parseWorldInfoEdit as pt, partsOf as q, DICE_READINGS as qt, MAX_PREVIEW_TEXT as r, FACTION_FILE_NAME as rt, worldOf as s, IMPORT_FOLDER as st, AuthoringTools as t, ITEM_FILE_NAME as tt, isReviewing as u, parseChoices as ut, populateClock as v, entriesOf as vt, populateLore as w, reserveLorebook as wt, populateItems as x, loadLorebook as xt, populateDice as y, isLorebookName as yt, ITEMS_DIR as z, IMPORT_COMMAND as zt };
5948
6052
 
5949
- //# sourceMappingURL=tools-Dy1fgP6B.js.map
6053
+ //# sourceMappingURL=authoring-tools-C_8ClUkP.js.map
package/lib/authoring.js CHANGED
@@ -1,8 +1,8 @@
1
- import { Nt as parseRelationEdit, Ot as InvalidEditProblems, a as authoredWorldOf, n as importHooks, r as importTools, s as isReviewing } from "./tools-Dy1fgP6B.js";
2
- import { _ as readWorldPrompt, g as listWorldPrompts, h as deleteWorldPrompt, m as PROSE_PROMPTS, v as writeWorldPrompt } from "./presets-gkBWAiVb.js";
3
- import { r as parsePlotsFile, s as formatIssue, v as shippedPromptsDirectory } from "./load-CVwJjIJ5.js";
4
- import { B as translateTools, C as readWorldEditor, F as loadWorldParts, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, R as presetTools, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, i as checkWorldPack, l as deleteAuthoredEntity, o as listWorldPacks, r as registerPackJail, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument, v as editWorldRelation } from "./pack-jail-2XztyYAX.js";
5
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-xHRCcGdb.js";
1
+ import { Lt as parseRelationEdit, Mt as InvalidEditProblems, a as importHooks, c as authoredWorldOf, n as limitAuthoringAgents, o as importTools, u as isReviewing } from "./authoring-tools-C_8ClUkP.js";
2
+ import { _ as readWorldPrompt, g as listWorldPrompts, h as deleteWorldPrompt, m as PROSE_PROMPTS, v as writeWorldPrompt } from "./presets-C3mhqqfz.js";
3
+ import { $ as shippedPromptsDirectory, H as formatIssue, R as parsePlotsFile } from "./hooks-B2EhBS_-.js";
4
+ import { C as readWorldEditor, F as loadWorldParts, H as translateTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, R as presetTools, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, i as checkWorldPack, l as deleteAuthoredEntity, o as listWorldPacks, r as registerPackJail, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument, v as editWorldRelation } from "./pack-jail-soI-In96.js";
5
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-CJPSe5LI.js";
6
6
  import { join, relative } from "node:path";
7
7
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
8
  import { readFile } from "node:fs/promises";
@@ -710,6 +710,7 @@ const inject = [
710
710
  "roleplayImport",
711
711
  "roleplayPrompts",
712
712
  "roleplayAuthoringLanguages",
713
+ "roleplayAuthoringTools",
713
714
  "tools",
714
715
  "systemPrompt"
715
716
  ];
@@ -745,6 +746,7 @@ function apply(ctx) {
745
746
  worldDirectory,
746
747
  reviewing
747
748
  });
749
+ limitAuthoringAgents(ctx, (chat) => authoredWorldOf(chat) === void 0 ? void 0 : "worldAuthoring");
748
750
  ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing));
749
751
  for (const [name, order, id] of [[
750
752
  "WORLD_AUTHORING_PERSONA",
@@ -3,6 +3,21 @@ import { SessionId } from "@deepseek-ai/dsh-session";
3
3
  import { ReasoningEffortId, createUserMessage, lastAssistantStreamChunk } from "@deepseek-ai/dsh-llm";
4
4
  import { appendDelegatedPolicyOverrides, applyChildComposition, captureDelegatedPolicyOverrides, childSessionMeta, resolveChildAgentOptions, resolveChildDepth } from "@deepseek-ai/dsh-subagent";
5
5
  import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
6
+ //#region src/shared/text.ts
7
+ /** Remove characters from either end without a backtracking regular expression. */
8
+ function trimCharacters(value, characters, edge = "both") {
9
+ let start = 0;
10
+ let end = value.length;
11
+ if (edge !== "end") while (start < end && characters.includes(value[start])) start += 1;
12
+ if (edge !== "start") while (end > start && characters.includes(value[end - 1])) end -= 1;
13
+ return value.slice(start, end);
14
+ }
15
+ /** A path-like name without its last extension. */
16
+ function withoutExtension(value) {
17
+ const dot = value.lastIndexOf(".");
18
+ return dot < 0 ? value : value.slice(0, dot);
19
+ }
20
+ //#endregion
6
21
  //#region src/host/agents/budget.ts
7
22
  /** Tokens a text of a number of characters comes to: a character of a script written without spaces takes about one and a half, of the others about a third. */
8
23
  function tokensOf$1(characters, language) {
@@ -65,6 +80,82 @@ function tokensOf(events) {
65
80
  const MAX_RUN_TEXT = 4e3;
66
81
  const MAX_RUN_PROMPT = 24e3;
67
82
  //#endregion
83
+ //#region src/shared/sampling.ts
84
+ /** The controls beyond temperature, which apply to the game master and the characters (the helpers that must be exact are never asked more freely). */
85
+ const SHARED_SAMPLING = [
86
+ "topP",
87
+ "topK",
88
+ "minP",
89
+ "frequencyPenalty",
90
+ "presencePenalty",
91
+ "repetitionPenalty"
92
+ ];
93
+ /** Each control's range and the value that leaves the choice to the model's server (and so is never sent). */
94
+ const SAMPLING_RANGES = {
95
+ master: {
96
+ min: 0,
97
+ max: 2
98
+ },
99
+ characters: {
100
+ min: 0,
101
+ max: 2
102
+ },
103
+ topP: {
104
+ min: 0,
105
+ max: 1,
106
+ neutral: 1
107
+ },
108
+ topK: {
109
+ min: 0,
110
+ max: 1e3,
111
+ neutral: 0
112
+ },
113
+ minP: {
114
+ min: 0,
115
+ max: 1,
116
+ neutral: 0
117
+ },
118
+ frequencyPenalty: {
119
+ min: -2,
120
+ max: 2,
121
+ neutral: 0
122
+ },
123
+ presencePenalty: {
124
+ min: -2,
125
+ max: 2,
126
+ neutral: 0
127
+ },
128
+ repetitionPenalty: {
129
+ min: 0,
130
+ max: 2,
131
+ neutral: 1
132
+ }
133
+ };
134
+ const SAMPLING_KEYS = Object.keys(SAMPLING_RANGES);
135
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
136
+ /** Reads the `sampling` object of a file or a request: every unknown name or out-of-range value is a problem, named with `where`. */
137
+ function parseSampling(value, where, problems) {
138
+ const sampling = {};
139
+ if (value === void 0 || value === null) return sampling;
140
+ if (!isRecord(value)) {
141
+ problems.push(`${where} must be an object`);
142
+ return sampling;
143
+ }
144
+ for (const key of Object.keys(value)) if (!Object.hasOwn(SAMPLING_RANGES, key)) problems.push(`${where}.${key} is not something that can be set (${SAMPLING_KEYS.join(", ")})`);
145
+ for (const key of SAMPLING_KEYS) {
146
+ const number = value[key];
147
+ if (number === void 0) continue;
148
+ const { min, max } = SAMPLING_RANGES[key];
149
+ if (typeof number !== "number" || !Number.isFinite(number) || number < min || number > max) problems.push(`${where}.${key} must be a number from ${min} to ${max}`);
150
+ else sampling[key] = number;
151
+ }
152
+ return sampling;
153
+ }
154
+ /** The controls of a chat's settings that are not neutral, as a model request carries them. */
155
+ function sharedSamplingOf(settings) {
156
+ return Object.fromEntries(SHARED_SAMPLING.flatMap((key) => settings[key] === SAMPLING_RANGES[key].neutral ? [] : [[key, settings[key]]]));
157
+ }
158
+ //#endregion
68
159
  //#region src/host/agents/child.ts
69
160
  /** The tool every child ends with: its arguments are the child's result. */
70
161
  const SUBMIT_TOOL = "submit_result";
@@ -93,6 +184,7 @@ function childSampling(settings, kind, estimate) {
93
184
  const ceiling = kind === "characters" || kind === "suggestions" ? settings.sampling.shortMaxTokens : settings.sampling.maxTokens;
94
185
  return {
95
186
  temperature: settings.sampling[kind],
187
+ ...kind === "characters" ? sharedSamplingOf(settings.sampling) : {},
96
188
  toolChoice: settings.sampling.tools,
97
189
  maxTokens: estimate === void 0 ? ceiling : Math.min(ceiling, outputBudget(estimate, settings.sampling.headroom)),
98
190
  priority: kind === "characters" || kind === "authoring" ? "foreground" : "background"
@@ -430,6 +522,6 @@ async function execute(task, stats) {
430
522
  return submitted.value;
431
523
  }
432
524
  //#endregion
433
- export { runChild as a, addTokens as c, tokensOf$1 as d, childTrace as i, currentTurn as l, childSampling as n, tokensOf as o, childSamplingOf as r, NO_TOKENS as s, childModel as t, estimateAnswer as u };
525
+ export { runChild as a, sharedSamplingOf as c, addTokens as d, currentTurn as f, withoutExtension as g, trimCharacters as h, childTrace as i, tokensOf as l, tokensOf$1 as m, childSampling as n, SAMPLING_RANGES as o, estimateAnswer as p, childSamplingOf as r, parseSampling as s, childModel as t, NO_TOKENS as u };
434
526
 
435
- //# sourceMappingURL=child-CFjnaTZt.js.map
527
+ //# sourceMappingURL=child-DsixtqTw.js.map