@dsh-agentic-roleplay/core 0.3.5 → 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 (52) hide show
  1. package/lib/{preset-ClQm7KPQ.js → authoring-tools-C_8ClUkP.js} +542 -261
  2. package/lib/authoring.js +7 -5
  3. package/lib/{child-CFjnaTZt.js → child-DsixtqTw.js} +94 -2
  4. package/lib/client.js +16938 -14212
  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-Cl6bjp7g.js → hooks-B2EhBS_-.js} +1884 -236
  11. package/lib/images.js +4 -4
  12. package/lib/index.js +1200 -242
  13. package/lib/{library-9JB9zw5a.js → library-COIktKBa.js} +4 -3
  14. package/lib/lorebook-author-tools-C-o0t4dL.js +694 -0
  15. package/lib/lorebook-authoring.js +69 -0
  16. package/lib/{settings-CA6icLL_.js → narration-BT9uvQry.js} +145 -2
  17. package/lib/orchestration.js +34 -21
  18. package/lib/{pack-jail-ClMpVc__.js → pack-jail-soI-In96.js} +170 -12
  19. package/lib/{packs-BC2A3geF.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-Dibp-LY9.js → preset-author-tools-C-X8G40s.js} +24 -18
  23. package/lib/preset-authoring.js +6 -3
  24. package/lib/{presets-DNjNxQL5.js → presets-C3mhqqfz.js} +50 -28
  25. package/lib/{reflection-Bju_LPFn.js → reflection-Btsj0ZLh.js} +51 -17
  26. package/package.json +3 -2
  27. package/packs/scene/map.html +1 -0
  28. package/packs/scene/strip.html +1 -0
  29. package/prompts/en/import/lorebook.md +8 -0
  30. package/prompts/en/import/style.md +1 -0
  31. package/prompts/en/lorebook/persona.md +1 -0
  32. package/prompts/en/lorebook/procedure.md +1 -0
  33. package/prompts/en/lorebook/welcome.md +1 -0
  34. package/prompts/en/preset/persona.md +1 -1
  35. package/prompts/en/preset/procedure.md +1 -1
  36. package/prompts/en/roleplay/character-lookup.md +1 -0
  37. package/prompts/en/roleplay/game-master.md +1 -1
  38. package/prompts/en/world/procedure.md +1 -1
  39. package/prompts/zh/import/lorebook.md +8 -0
  40. package/prompts/zh/import/style.md +1 -0
  41. package/prompts/zh/lorebook/persona.md +1 -0
  42. package/prompts/zh/lorebook/procedure.md +1 -0
  43. package/prompts/zh/lorebook/welcome.md +1 -0
  44. package/prompts/zh/preset/persona.md +1 -1
  45. package/prompts/zh/preset/procedure.md +1 -1
  46. package/prompts/zh/roleplay/character-lookup.md +1 -0
  47. package/prompts/zh/roleplay/game-master.md +1 -1
  48. package/prompts/zh/world/procedure.md +1 -1
  49. package/lib/hooks-DdO_tNhu.js +0 -1060
  50. package/lib/language-BgyxtB2h.js +0 -38
  51. package/lib/load-Clkl0T7C.js +0 -486
  52. package/lib/narration-DK2kiIjE.js +0 -141
@@ -0,0 +1,69 @@
1
+ import { St as lorebookDirectory, n as limitAuthoringAgents } from "./authoring-tools-C_8ClUkP.js";
2
+ import "./hooks-B2EhBS_-.js";
3
+ import { c as lorebookOfChat, i as lorebookAuthorTools, n as LorebookReader, o as pendingTargets, r as lorebookApproval } from "./lorebook-author-tools-C-o0t4dL.js";
4
+ import { join } from "node:path";
5
+ import { existsSync, readdirSync } from "node:fs";
6
+ //#region src/lorebook-authoring.ts
7
+ const name = "@dsh-agentic-roleplay/core/lorebook-authoring";
8
+ const inject = [
9
+ "roleplayRoot",
10
+ "roleplayImport",
11
+ "roleplayPrompts",
12
+ "roleplayAuthoringLanguages",
13
+ "roleplayAuthoringTools",
14
+ "tools",
15
+ "systemPrompt"
16
+ ];
17
+ /** The lorebook authoring chat: reads and writes the entries of one library lorebook, each write approved by the person. */
18
+ function apply(ctx) {
19
+ const library = () => ctx.roleplayRoot.path;
20
+ const reader = new LorebookReader(library);
21
+ const prompting = {
22
+ prompts: () => ctx.roleplayPrompts,
23
+ languages: () => ctx.roleplayAuthoringLanguages
24
+ };
25
+ for (const tool of lorebookAuthorTools(reader, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
26
+ const directoryOf = (chat) => {
27
+ const book = lorebookOfChat(chat);
28
+ return book === void 0 ? void 0 : lorebookDirectory(library(), book);
29
+ };
30
+ const carries = (chat) => {
31
+ const directory = directoryOf(chat);
32
+ return directory !== void 0 && existsSync(join(directory, "lore")) && readdirSync(join(directory, "lore")).length > 0;
33
+ };
34
+ const waiting = (chat) => {
35
+ const directory = directoryOf(chat);
36
+ return directory === void 0 ? {
37
+ ids: [],
38
+ rules: false
39
+ } : pendingTargets(directory);
40
+ };
41
+ limitAuthoringAgents(ctx, (chat) => lorebookOfChat(chat) === void 0 ? void 0 : "lorebookAuthoring");
42
+ ctx.on("tools/pre-execute", (exec, next) => lorebookApproval(exec, next, {
43
+ carries,
44
+ waiting
45
+ }));
46
+ const languageOf = (context) => {
47
+ const chat = context.agent?.session.id;
48
+ const book = chat === void 0 ? void 0 : lorebookOfChat(chat);
49
+ return book === void 0 ? "en" : ctx.roleplayAuthoringLanguages.get(`lorebook:${book}`);
50
+ };
51
+ for (const [section, order, id] of [[
52
+ "LOREBOOK_AUTHORING_PERSONA",
53
+ ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),
54
+ "lorebook/persona"
55
+ ], [
56
+ "LOREBOOK_AUTHORING_PROCEDURE",
57
+ ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_SUFFIX"),
58
+ "lorebook/procedure"
59
+ ]]) ctx.systemPrompt.section({
60
+ name: section,
61
+ order,
62
+ interpolate: false,
63
+ text: (context) => ctx.roleplayPrompts.text(id, languageOf(context))
64
+ });
65
+ }
66
+ //#endregion
67
+ export { apply, inject, name };
68
+
69
+ //# sourceMappingURL=lorebook-authoring.js.map
@@ -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
@@ -214,6 +216,12 @@ const SETTINGS_SPEC = {
214
216
  sampling: {
215
217
  master: ratio(0, 2, .7),
216
218
  characters: ratio(0, 2, .8),
219
+ topP: ratio(0, 1, 1),
220
+ topK: integer(0, 1e3, 0),
221
+ minP: ratio(0, 1, 0),
222
+ frequencyPenalty: ratio(-2, 2, 0),
223
+ presencePenalty: ratio(-2, 2, 0),
224
+ repetitionPenalty: ratio(0, 2, 1),
217
225
  suggestions: ratio(0, 2, .2),
218
226
  authoring: ratio(0, 2, .4),
219
227
  records: ratio(0, 2, .1),
@@ -378,6 +386,141 @@ function parseSettings(value) {
378
386
  };
379
387
  }
380
388
  //#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 };
389
+ //#region src/host/sessions/settings.ts
390
+ const SETTINGS_FILE = "settings.json";
391
+ const known = /* @__PURE__ */ new Map();
392
+ let childReasoning = "";
393
+ /** The thinking level helpers get when a chat's own setting is empty (the profile's choice); returns the function that takes it back. */
394
+ function useChildReasoning(level) {
395
+ childReasoning = level;
396
+ return () => {
397
+ childReasoning = "";
398
+ };
399
+ }
400
+ /** The settings are not acceptable; `problems` say what to fix. */
401
+ var InvalidSettingsError = class extends Error {
402
+ problems;
403
+ constructor(problems) {
404
+ super(`the settings are not acceptable: ${problems.join("; ")}`);
405
+ this.problems = problems;
406
+ }
407
+ };
408
+ /**
409
+ * The settings of the session in `folder`; a session that has none yet has the defaults.
410
+ * @throws {InvalidSettingsError} when the file exists and is not valid.
411
+ */
412
+ function readSettings(folder) {
413
+ const file = join(folder, SETTINGS_FILE);
414
+ if (!existsSync(file)) return { ...DEFAULT_SETTINGS };
415
+ let value;
416
+ try {
417
+ value = JSON.parse(readFileSync(file, "utf8"));
418
+ } catch (error) {
419
+ throw new InvalidSettingsError([`${SETTINGS_FILE} is not valid JSON (${error instanceof Error ? error.message : String(error)})`]);
420
+ }
421
+ const parsed = parseSettings(value);
422
+ if (!parsed.ok) throw new InvalidSettingsError(parsed.problems);
423
+ return parsed.value;
424
+ }
425
+ /**
426
+ * Store the settings of the session in `folder`, replacing what was there.
427
+ * @throws {InvalidSettingsError} when the value is not acceptable; nothing is written then.
428
+ */
429
+ function writeSettings(folder, value) {
430
+ const parsed = parseSettings(value);
431
+ if (!parsed.ok) throw new InvalidSettingsError(parsed.problems);
432
+ const file = join(folder, SETTINGS_FILE);
433
+ const temporary = `${file}.${process.pid}.tmp`;
434
+ writeFileSync(temporary, `${JSON.stringify(parsed.value, null, 2)}\n`);
435
+ renameSync(temporary, file);
436
+ known.delete(folder);
437
+ return parsed.value;
438
+ }
439
+ /**
440
+ * The settings to use right now. Called before each use, so an edit to the file applies at the
441
+ * next round, step or run without a restart; the file is parsed again only when it changed.
442
+ * A file that is not valid is reported once through `problem` and the last good settings
443
+ * (the defaults when there were none) stay in force, so a typo cannot stop a story in the middle.
444
+ */
445
+ function liveSettings(folder, problem = () => void 0) {
446
+ const value = loadedSettings(folder, problem);
447
+ return value.reasoning.children === "" && childReasoning !== "" ? {
448
+ ...value,
449
+ reasoning: {
450
+ ...value.reasoning,
451
+ children: childReasoning
452
+ }
453
+ } : value;
454
+ }
455
+ function loadedSettings(folder, problem) {
456
+ let modified = -1;
457
+ try {
458
+ modified = statSync(join(folder, SETTINGS_FILE)).mtimeMs;
459
+ } catch {}
460
+ const last = known.get(folder);
461
+ if (last?.modified === modified) return last.value;
462
+ try {
463
+ const value = readSettings(folder);
464
+ known.set(folder, {
465
+ modified,
466
+ value
467
+ });
468
+ return value;
469
+ } catch (error) {
470
+ if (!(error instanceof InvalidSettingsError)) throw error;
471
+ problem(`${error.message} (the last good settings stay in force)`);
472
+ const value = last?.value ?? { ...DEFAULT_SETTINGS };
473
+ known.set(folder, {
474
+ modified,
475
+ value
476
+ });
477
+ return value;
478
+ }
479
+ }
480
+ //#endregion
481
+ //#region src/shared/narration.ts
482
+ const OPEN = "<roleplay-output>";
483
+ const CLOSE = "</roleplay-output>";
484
+ const PREVIEW_OPEN = "<roleplay-preview>";
485
+ const PREVIEW_CLOSE = "</roleplay-preview>";
486
+ /** 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. */
487
+ function encodePreview(text) {
488
+ return `${PREVIEW_OPEN}${JSON.stringify({ text })}${PREVIEW_CLOSE}`;
489
+ }
490
+ function encodeOutput(output) {
491
+ return `${OPEN}${JSON.stringify(output)}${CLOSE}`;
492
+ }
493
+ function isSegment(value) {
494
+ if (typeof value !== "object" || value === null) return false;
495
+ const segment = value;
496
+ if (segment["type"] === "narration") return typeof segment["text"] === "string";
497
+ return segment["type"] === "utterance" && typeof segment["character"] === "string" && typeof segment["name"] === "string" && typeof segment["text"] === "string";
498
+ }
499
+ /** The output encoded in a tool result's text, or nothing when the text carries none. */
500
+ function decodeOutput(text) {
501
+ const start = text.indexOf(OPEN);
502
+ const end = text.indexOf(CLOSE, start + 17);
503
+ if (start < 0 || end < 0) return void 0;
504
+ try {
505
+ const value = JSON.parse(text.slice(start + 17, end));
506
+ const segments = value["segments"];
507
+ if (!Array.isArray(segments) || !segments.every(isSegment) || typeof value["repaired"] !== "boolean") return void 0;
508
+ const ooc = value["ooc"];
509
+ const ruled = typeof ooc === "object" && ooc !== null && typeof ooc["legal"] === "boolean" && typeof ooc["note"] === "string" ? ooc : void 0;
510
+ const timelineNode = typeof value["timelineNode"] === "string" ? value["timelineNode"] : void 0;
511
+ 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")) : [];
512
+ return {
513
+ segments,
514
+ repaired: value["repaired"],
515
+ ...ruled === void 0 ? {} : { ooc: ruled },
516
+ ...rolls.length === 0 ? {} : { rolls },
517
+ ...timelineNode === void 0 ? {} : { timelineNode }
518
+ };
519
+ } catch {
520
+ return;
521
+ }
522
+ }
523
+ //#endregion
524
+ 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
525
 
383
- //# sourceMappingURL=settings-CA6icLL_.js.map
526
+ //# sourceMappingURL=narration-BT9uvQry.js.map
@@ -1,17 +1,13 @@
1
1
  import { n as chatSessionId, r as roleplaySessionOf, t as promptFor } from "./access-EbNdZFbk.js";
2
- import { y as INTENT_STATUSES } from "./presets-DNjNxQL5.js";
3
- import { a as whereabouts, g as referent, h as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-Bju_LPFn.js";
4
- import "./settings-CA6icLL_.js";
5
- import { C as ReflectionRefusedError } from "./load-Clkl0T7C.js";
6
- import { B as RESULTS, F as describeWhen, H as languageOf, M as ClockError, S as MAX_OOC_ANSWER, U as translator, m as createTools$1, p as PREVIEW_TOOL, u as externalGiven, w as toolEnabled, x as AUTHORING_NEEDS, z as zoneOf } from "./deliver-Cl6bjp7g.js";
7
- import { a as liveSettings } from "./narration-DK2kiIjE.js";
8
- import { a as runChild, d as tokensOf, i as childTrace, l as currentTurn, n as childSampling, t as childModel, u as estimateAnswer } from "./child-CFjnaTZt.js";
9
- import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-9JB9zw5a.js";
10
- import { a as wrongLanguage } from "./language-BgyxtB2h.js";
11
- import { _ as API_PREFIX } from "./packs-BC2A3geF.js";
12
- import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-DIEgETzU.js";
13
- import { a as writeVerdicts, i as readVerdicts, n as installHooks, r as storesOf } from "./hooks-DdO_tNhu.js";
14
- import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-DnNEG_Mn.js";
2
+ import { b as INTENT_STATUSES } from "./presets-C3mhqqfz.js";
3
+ import { a as whereabouts, g as referent, h as sameWords, n as memoryReflector, r as recordFailure, s as Timelines, t as dueReflection } from "./reflection-Btsj0ZLh.js";
4
+ import { a as liveSettings } from "./narration-BT9uvQry.js";
5
+ import { E as RESULTS, F as wrongLanguage, S as ClockError, T as zoneOf, c as AUTHORING_NEEDS, ct as translator, d as storesOf, g as writeVerdicts, h as readVerdicts, l as toolEnabled, n as installHooks, o as PREVIEW_TOOL, r as externalGiven, rt as ReflectionRefusedError, s as createTools$1, st as languageOf, u as MAX_OOC_ANSWER, w as describeWhen } from "./hooks-B2EhBS_-.js";
6
+ import { a as runChild, f as currentTurn, i as childTrace, m as tokensOf, n as childSampling, p as estimateAnswer, t as childModel } from "./child-DsixtqTw.js";
7
+ import { b as slug, t as addToLibrary, x as uniqueKey } from "./library-COIktKBa.js";
8
+ import { _ as API_PREFIX } from "./packs-CJPSe5LI.js";
9
+ import { i as updateImage, r as listGallery, t as describeGalleryImage } from "./gallery-CDYKJf_O.js";
10
+ import { n as interpretImage, s as presentedFor, t as runImagePresenter } from "./presenter-agent-Gu34bZwd.js";
15
11
  import { join } from "node:path";
16
12
  import { existsSync } from "node:fs";
17
13
  import { SessionId } from "@deepseek-ai/dsh-session";
@@ -25,7 +21,11 @@ const RESOURCE_TOOLS = [
25
21
  "list_mcp_resource_templates",
26
22
  "read_mcp_resource"
27
23
  ];
28
- const NAMESPACED = /^mcp__(.+?)__.+$/;
24
+ function serverOf(name) {
25
+ if (!name.startsWith("mcp__")) return [];
26
+ const end = name.indexOf("__", 5);
27
+ return end <= 5 || end + 2 >= name.length ? [] : [name.slice(5, end)];
28
+ }
29
29
  /**
30
30
  * What an agent is told about MCP resources: nothing unless it can see a resource tool, since the plugin's own paragraph names the tools
31
31
  * and servers to every agent whether or not it was given them, and an agent that is told of a tool it lacks goes looking for it. The servers are
@@ -34,7 +34,7 @@ const NAMESPACED = /^mcp__(.+?)__.+$/;
34
34
  function resourceHint(visible, registered, tr) {
35
35
  const tools = RESOURCE_TOOLS.filter((name) => visible.includes(name));
36
36
  if (tools.length === 0) return "";
37
- const servers = [...new Set(registered.flatMap((name) => NAMESPACED.exec(name)?.[1] ?? []))].sort();
37
+ const servers = [...new Set(registered.flatMap(serverOf))].sort((a, b) => a.localeCompare(b));
38
38
  return servers.length === 0 ? tr("## MCP resource servers\n\nUse {tools} with the server argument naming an MCP server.", { tools: tools.join(", ") }) : tr("## MCP resource servers\n\nUse {tools} with one of these names as the server argument: {servers}.", {
39
39
  tools: tools.join(", "),
40
40
  servers: JSON.stringify(servers)
@@ -614,6 +614,8 @@ function factionStrategist(deps) {
614
614
  }
615
615
  //#endregion
616
616
  //#region src/host/authoring/author-agent.ts
617
+ /** How many calls of the tools of other plugins the author may make on top of its own budget. */
618
+ const EXTERNAL_CALLS = 10;
617
619
  /** A made-up thing in one edit: its name, description and the handful of fields a character, place or item carries. */
618
620
  const THING_TEXTS = 14;
619
621
  const THING_TEXT_CHARS = 300;
@@ -857,6 +859,7 @@ function worldAuthor(deps) {
857
859
  if (parent === void 0) throw new Error(`no agent for chat ${chat}`);
858
860
  return parent;
859
861
  };
862
+ const given = (parent) => deps.external?.(parent) ?? [];
860
863
  return {
861
864
  async create(job, signal) {
862
865
  const parent = parentOf(job.chat);
@@ -872,6 +875,7 @@ function worldAuthor(deps) {
872
875
  persona: promptFor(parent, "world/author", job.store.settings().prompts.language),
873
876
  prompt: createPrompt(job, authoring.perTurn),
874
877
  tools: authorTools(job, work, "create", authoring),
878
+ external: given(parent),
875
879
  result: CREATE_RESULT,
876
880
  beforeSubmit: (value) => {
877
881
  const { outcome } = value;
@@ -880,7 +884,7 @@ function worldAuthor(deps) {
880
884
  const errors = errorsAbout(job.store, work);
881
885
  return errors.length === 0 ? void 0 : `what you made is not usable yet; fix it with edit_world:\n${describeFindings(errors).join("\n")}`;
882
886
  },
883
- maxCalls: 30
887
+ maxCalls: 30 + (given(parent).length > 0 ? EXTERNAL_CALLS : 0)
884
888
  });
885
889
  const label = names(job.store);
886
890
  const created = work.created.map((entry) => ({
@@ -915,6 +919,7 @@ function worldAuthor(deps) {
915
919
  persona: promptFor(parent, "world/consolidate", job.store.settings().prompts.language),
916
920
  prompt: consolidationPrompt(job),
917
921
  tools: authorTools(job, work, "consolidate", authoring),
922
+ external: given(parent),
918
923
  result: CONSOLIDATE_RESULT,
919
924
  beforeSubmit: (value) => {
920
925
  if (!value.complete) return void 0;
@@ -923,7 +928,7 @@ function worldAuthor(deps) {
923
928
  const errors = lintWorld(job.store.story).filter((finding) => finding.severity === "error");
924
929
  return errors.length === 0 ? void 0 : `the world still shows errors:\n${describeFindings(errors).join("\n")}`;
925
930
  },
926
- maxCalls: 60
931
+ maxCalls: 60 + (given(parent).length > 0 ? EXTERNAL_CALLS : 0)
927
932
  });
928
933
  if (!result.complete) throw new Error(`not everything could be fitted in: ${result.notes}`);
929
934
  return {
@@ -939,6 +944,11 @@ const PROTOCOL_SECTION = "roleplay:protocol";
939
944
  const PERSONA_SECTION = "roleplay:persona";
940
945
  //#endregion
941
946
  //#region src/host/dice/describe.ts
947
+ const sentenceBody = (value) => {
948
+ let end = value.length;
949
+ while (end > 0 && (value[end - 1] === "." || /\s/u.test(value[end - 1]))) end -= 1;
950
+ return value.slice(0, end);
951
+ };
942
952
  /** The checks of a story as the game master is told of them: when each is used, what it rolls and what it needs. The result's bands are told by the roll itself. */
943
953
  function describeChecks(checks, tr) {
944
954
  if (checks.length === 0) return tr("No checks are defined: use roll_dice only.");
@@ -952,7 +962,7 @@ function describeChecks(checks, tr) {
952
962
  return `${tr("- {key} ({name}): {use}", {
953
963
  key: check.key,
954
964
  name: check.name,
955
- use: check.use.replace(/[.\s]+$/, "")
965
+ use: sentenceBody(check.use)
956
966
  })}. ${needs.join(" ")}`;
957
967
  });
958
968
  return [tr("The checks of this story:"), ...lines].join("\n");
@@ -1781,7 +1791,7 @@ function asSpoken(segments, spoken) {
1781
1791
  */
1782
1792
  function checkedOutput(narrationChecker, language, state, segments, silent) {
1783
1793
  const problems = [...segments.flatMap((segment, index) => segment.type === "utterance" && segment.character === "" ? [`segment ${index + 1}: an utterance needs the character who says it`] : []), ...narrationChecker.check(segments, state.utterances)];
1784
- const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") });
1794
+ const wording = wrongLanguage(language, { narration: segments.flatMap((segment) => segment.type === "narration" ? [segment.text] : []).join(" ") }, { strays: true });
1785
1795
  if (problems.length === 0 && wording !== void 0 && !silent && state.refused < 2) {
1786
1796
  state.refused += 1;
1787
1797
  throw new Error(`the output is not acceptable: ${wording}. Deliver it again with the narration corrected; utterances may not be touched`);
@@ -2081,7 +2091,7 @@ var TurnEngine = class {
2081
2091
  });
2082
2092
  if (keys.length === 0) throw new Error("there is no character to activate");
2083
2093
  if (keys.length > most) throw new Error(`${keys.length} characters were asked, which is more than one round allows (${most}): ask only those the moment actually reaches, and the others in a later round if the story comes to them`);
2084
- const signature = `${[...keys].sort().join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
2094
+ const signature = `${[...keys].sort((a, b) => a.localeCompare(b)).join(",")}|${situation.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()}`;
2085
2095
  if (repeatsEarlier(signature, state.asked)) throw new Error("the same characters were already asked about the same situation in this message, so nothing new would come of it: say what changed, ask others, or deliver the output with narrate");
2086
2096
  state.situation = situation;
2087
2097
  state.cast = cast;
@@ -2895,7 +2905,10 @@ function apply(ctx) {
2895
2905
  ctx.effect(() => ctx.roleplayOrchestration.replace({ judge: triggerJudge({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: trigger judge");
2896
2906
  ctx.effect(() => ctx.roleplayOrchestration.replace({ strategist: factionStrategist({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: faction strategist");
2897
2907
  ctx.effect(() => ctx.roleplayOrchestration.replace({ reflector: memoryReflector({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: reflection");
2898
- ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: world author");
2908
+ ctx.effect(() => ctx.roleplayOrchestration.replace({ author: worldAuthor({
2909
+ agentOf: (chat) => ctx.agents.get(SessionId(chat)),
2910
+ external: (parent) => ctx.get("roleplayAuthoringTools")?.given(parent.ctx.tools, "worldAuthor") ?? []
2911
+ }) }), "roleplay: world author");
2899
2912
  ctx.effect(() => ctx.roleplayOrchestration.replace({ suggester: suggestionWriter({ agentOf: (chat) => ctx.agents.get(SessionId(chat)) }) }), "roleplay: suggestions");
2900
2913
  ctx.effect(() => ctx.roleplayState.bind((agentSessionId) => {
2901
2914
  const id = roleplaySessionOf(agentSessionId);
@@ -1,10 +1,12 @@
1
- import { $ as LOCATION_FILE_NAME, B as FACTIONS_DIR, D as loadTriggers, E as TRIGGERS_FILE_NAME, F as loadLore, G as extractStyleFrom, H as CHARACTERS_DIR, I as LOCATIONS_DIR, J as loadVariables, K as withPlayer, L as loadLocations, M as loadCalendar, P as LORE_DIR, Q as parseLoreFile, R as ITEMS_DIR, U as loadCharacters, V as loadFactions, W as subfolders, Z as LORE_FILE_NAME, a as worldOf, at as CHARACTER_FILE_NAME, b as populateLocations, et as parseLocationFile, f as loadValidatedWorld, it as parseFactionFile, m as populateCharacters, mt as InvalidEditProblems, n as contextOf, nt as parseItemFile, o as authoredWorldOf, ot as parseCharacterFile, rt as FACTION_FILE_NAME, st as IMPORT_FOLDER, t as readPreset, tt as ITEM_FILE_NAME, v as populateItems, w as populateVariables, z as loadItems } from "./preset-ClQm7KPQ.js";
2
- import { _ as writeWorldPrompt } from "./presets-DNjNxQL5.js";
3
- import { S as InvalidWorldError, _ as shippedLanguages, c as formatIssue, i as plotReferenceProblems, n as loadPlots, r as parsePlotsFile, t as PLOTS_FILE_NAME, u as PROMPTS_FOLDER } from "./load-Clkl0T7C.js";
4
- import { c as referenceImagePath, v as mapLimit } from "./library-9JB9zw5a.js";
5
- import { i as textLanguage, n as STORY_LANGUAGES, r as isStoryLanguage, t as LANGUAGE_NAMES } from "./language-BgyxtB2h.js";
6
- import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-BC2A3geF.js";
7
- import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-DJ48HxPI.js";
1
+ import { $ as LOCATION_FILE_NAME, A as loadTriggers, At as parseLoreFile, B as loadItems, C as populateLocations, D as populateVariables, Dt as LORE_DIR, F as loadCalendar, G as extractStyleFrom, H as loadFactions, J as withPlayer, L as LOCATIONS_DIR, Mt as InvalidEditProblems, Ot as loadLore, R as loadLocations, U as CHARACTERS_DIR, V as FACTIONS_DIR, W as loadCharacters, X as loadVariables, _ as populateCharacters, at as CHARACTER_FILE_NAME, c as authoredWorldOf, dt as WORLD_FILE_NAME, et as parseLocationFile, ft as parseWorldFile, h as knowsCharacter, i as contextOf, it as parseFactionFile, jt as subfolders, k as TRIGGERS_FILE_NAME, kt as LORE_FILE_NAME, m as loadValidatedWorld, nt as parseItemFile, ot as parseCharacterFile, rt as FACTION_FILE_NAME, s as worldOf, st as IMPORT_FOLDER, tt as ITEM_FILE_NAME, x as populateItems, z as ITEMS_DIR } from "./authoring-tools-C_8ClUkP.js";
2
+ import { v as writeWorldPrompt } from "./presets-C3mhqqfz.js";
3
+ import { f as parseSwitchboard } from "./narration-BT9uvQry.js";
4
+ import { G as PROMPTS_FOLDER, H as formatIssue, I as PLOTS_FILE_NAME, L as loadPlots, M as STORY_LANGUAGES, N as isStoryLanguage, P as textLanguage, Q as shippedLanguages, R as parsePlotsFile, j as LANGUAGE_NAMES, nt as InvalidWorldError, z as plotReferenceProblems } from "./hooks-B2EhBS_-.js";
5
+ import { s as parseSampling } from "./child-DsixtqTw.js";
6
+ import { c as referenceImagePath, v as mapLimit } from "./library-COIktKBa.js";
7
+ import { n as readPreset } from "./preset-3zn8xme7.js";
8
+ import { _ as API_PREFIX, a as packIds, d as packPath, f as readPack, h as PACK_MEDIA_TYPES, l as isPackId } from "./packs-CJPSe5LI.js";
9
+ import { a as uploadReferenceImage, t as generateReferenceImage } from "./generator-BR1ugzln.js";
8
10
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
9
11
  import { existsSync, lstatSync, statSync } from "node:fs";
10
12
  import { randomUUID } from "node:crypto";
@@ -58,7 +60,17 @@ const MIN_USES = 3;
58
60
  const capitalised = (word) => /^\p{Lu}[\p{L}'’-]{2,}$/u.test(word) && !STOP.has(word.toLowerCase());
59
61
  /** The parts of a name written "Place - Room": each part is a name of its own, and so is the whole. */
60
62
  function partsOfName(name) {
61
- return name.split(/\s+[-–—]\s+/).map((part) => part.trim()).filter((part) => part !== "");
63
+ const parts = [];
64
+ let start = 0;
65
+ for (let at = 1; at < name.length - 1; at += 1) {
66
+ if (!"-–—".includes(name[at]) || !/\s/u.test(name[at - 1]) || !/\s/u.test(name[at + 1])) continue;
67
+ const part = name.slice(start, at).trim();
68
+ if (part !== "") parts.push(part);
69
+ start = at + 1;
70
+ }
71
+ const last = name.slice(start).trim();
72
+ if (last !== "") parts.push(last);
73
+ return parts;
62
74
  }
63
75
  /**
64
76
  * Words of the world that recur inside other names and texts and so have to be rendered once: the parts of names ("Iron Stag Inn" in "Iron Stag Inn - Bar") and capitalised
@@ -604,6 +616,131 @@ function translateTools(worlds, settings, prompting) {
604
616
  })];
605
617
  }
606
618
  //#endregion
619
+ //#region src/host/worlds/world-info.ts
620
+ async function replaceFile$2(file, text) {
621
+ const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
622
+ try {
623
+ const { mode } = await stat(file);
624
+ await writeFile(temporary, text, { mode });
625
+ await chmod(temporary, mode);
626
+ await rename(temporary, file);
627
+ } catch (error) {
628
+ await rm(temporary, { force: true });
629
+ throw error;
630
+ }
631
+ }
632
+ const textOf$1 = (value) => typeof value === "string" ? value : "";
633
+ const toolsOf = (value) => {
634
+ const board = value === void 0 ? {} : parseSwitchboard(value, "tools");
635
+ return typeof board === "string" ? {} : board;
636
+ };
637
+ function infoOf(document) {
638
+ const opening = document["opening_message"];
639
+ const parts = Array.isArray(opening) && opening.some((part) => typeof part === "object" && part !== null && part["type"] === "utterance");
640
+ const plain = typeof opening === "string" ? opening : Array.isArray(opening) ? opening.map((part) => textOf$1(part?.["text"])).filter((text) => text !== "").join("\n\n") : "";
641
+ const metadata = typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {};
642
+ const author = typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {};
643
+ const rules = document["rules"];
644
+ return {
645
+ name: textOf$1(document["name"]),
646
+ description: textOf$1(document["description"]),
647
+ tags: Array.isArray(metadata["tags"]) ? metadata["tags"].filter((tag) => typeof tag === "string") : [],
648
+ rules: typeof rules === "string" ? [rules] : Array.isArray(rules) ? rules.filter((rule) => typeof rule === "string") : [],
649
+ opening: plain,
650
+ openingParts: parts,
651
+ authorName: textOf$1(author["name"]),
652
+ authorUrl: textOf$1(author["url"]),
653
+ timeZone: textOf$1(document["time_zone"]),
654
+ startingTime: textOf$1(document["starting_time"]),
655
+ preset: textOf$1(document["preset"]),
656
+ lorebooks: Array.isArray(document["lorebooks"]) ? document["lorebooks"].filter((name) => typeof name === "string") : [],
657
+ version: typeof document["version"] === "number" ? String(document["version"]) : textOf$1(document["version"]),
658
+ sampling: parseSampling(document["sampling"], "sampling", []),
659
+ tools: toolsOf(document["tools"]),
660
+ alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
661
+ title: textOf$1(entry["title"]),
662
+ text: entry["text"],
663
+ ...textOf$1(entry["character"]) === "" ? {} : { character: textOf$1(entry["character"]) }
664
+ }] : []) : []
665
+ };
666
+ }
667
+ async function readDocument(directory) {
668
+ const text = await readFile(join(directory, WORLD_FILE_NAME), "utf8");
669
+ return {
670
+ text,
671
+ document: JSON.parse(text.replace(/^/, ""))
672
+ };
673
+ }
674
+ async function readWorldInfo(directory) {
675
+ return infoOf((await readDocument(directory)).document);
676
+ }
677
+ function setOrRemove(document, key, value) {
678
+ if (value === "") delete document[key];
679
+ else document[key] = value;
680
+ }
681
+ /**
682
+ * Changes the fields of `world.json` the edit names and nothing else, keeping the file's other fields and its indentation. The result is read
683
+ * back as the world will be read before it is written.
684
+ * @throws {InvalidEditProblems} when the world would no longer be valid.
685
+ */
686
+ async function editWorldInfo(directory, edit) {
687
+ const { text, document } = await readDocument(directory);
688
+ const before = infoOf(document);
689
+ if (edit.opening !== void 0 && before.openingParts && edit.opening !== before.opening) throw new InvalidEditProblems(["the opening has lines spoken by characters: change it in the file, or ask the authoring assistant"]);
690
+ if (edit.name !== void 0) document["name"] = edit.name;
691
+ if (edit.description !== void 0) document["description"] = edit.description;
692
+ if (edit.tags !== void 0) document["metadata"] = {
693
+ ...typeof document["metadata"] === "object" && document["metadata"] !== null ? document["metadata"] : {},
694
+ tags: edit.tags
695
+ };
696
+ if (edit.rules !== void 0) {
697
+ if (edit.rules.length === 0) delete document["rules"];
698
+ else document["rules"] = edit.rules;
699
+ }
700
+ if (edit.opening !== void 0 && !before.openingParts) setOrRemove(document, "opening_message", edit.opening);
701
+ if (edit.authorName !== void 0 || edit.authorUrl !== void 0) {
702
+ const name = edit.authorName ?? before.authorName;
703
+ const url = edit.authorUrl ?? before.authorUrl;
704
+ if (name === "" && url !== "") throw new InvalidEditProblems(["an author link needs the author's name"]);
705
+ if (name === "") delete document["author"];
706
+ else document["author"] = {
707
+ ...typeof document["author"] === "object" && document["author"] !== null ? document["author"] : {},
708
+ name,
709
+ ...url === "" ? {} : { url }
710
+ };
711
+ if (url === "" && typeof document["author"] === "object") delete document["author"]["url"];
712
+ }
713
+ if (edit.timeZone !== void 0) setOrRemove(document, "time_zone", edit.timeZone);
714
+ if (edit.startingTime !== void 0) setOrRemove(document, "starting_time", edit.startingTime);
715
+ if (edit.version !== void 0) setOrRemove(document, "version", edit.version);
716
+ if (edit.preset !== void 0) setOrRemove(document, "preset", edit.preset);
717
+ if (edit.lorebooks !== void 0) {
718
+ if (edit.lorebooks.length === 0) delete document["lorebooks"];
719
+ else document["lorebooks"] = edit.lorebooks;
720
+ }
721
+ if (edit.alternateOpenings !== void 0) {
722
+ if (edit.alternateOpenings.length === 0) delete document["alternate_openings"];
723
+ else document["alternate_openings"] = edit.alternateOpenings.map((entry) => ({
724
+ title: entry.title === "" ? entry.text.slice(0, 40) : entry.title,
725
+ text: entry.text,
726
+ ...entry.character === void 0 || entry.character === "" ? {} : { character: entry.character }
727
+ }));
728
+ }
729
+ if (edit.sampling !== void 0) {
730
+ if (Object.keys(edit.sampling).length === 0) delete document["sampling"];
731
+ else document["sampling"] = edit.sampling;
732
+ }
733
+ if (edit.tools !== void 0) {
734
+ if (Object.keys(edit.tools).length === 0) delete document["tools"];
735
+ else document["tools"] = edit.tools;
736
+ }
737
+ const next = JSON.stringify(document, null, /^([ \t]+)"/m.exec(text)?.[1] ?? " ") + (text.endsWith("\n") ? "\n" : "");
738
+ const parsed = parseWorldFile(next);
739
+ if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
740
+ await replaceFile$2(join(directory, WORLD_FILE_NAME), next);
741
+ return infoOf(document);
742
+ }
743
+ //#endregion
607
744
  //#region src/host/import/preset-tools.ts
608
745
  const PRESET_TOOL = "import_preset";
609
746
  const PRESET_FILE = "preset.json";
@@ -614,7 +751,7 @@ const presetMessage = () => `Apply the narration preset I uploaded to this world
614
751
  function presetTools(worlds, settings, prompting) {
615
752
  return [defineTool({
616
753
  name: PRESET_TOOL,
617
- description: `Turn the narration preset the person uploaded to this world (${PRESET_PATH}) into the world's prose prompts: how the narration is written and how the characters speak and behave. Rules of the game, formats and scripts in the preset are not carried. It replaces the world's own versions of those prompts, so the person is asked first.`,
754
+ description: `Turn the narration preset the person uploaded to this world (${PRESET_PATH}) into the world's prose prompts: how the narration is written and how the characters speak and behave. Rules of the game, formats and scripts in the preset are not carried; the sampling it asks (temperature and so on) is written into the world's suggested sampling. It replaces the world's own versions of those prompts, so the person is asked first.`,
618
755
  parameters: { file: {
619
756
  type: "string",
620
757
  required: true,
@@ -639,14 +776,20 @@ function presetTools(worlds, settings, prompting) {
639
776
  const text = (id, variables) => prompting.prompts().text(id, language, variables);
640
777
  const made = await extractStyleFrom(contextOf(exec, settings(), text), preset.name, preset.pieces);
641
778
  for (const { id, text: body } of made.prompts) for (const tag of shippedLanguages()) await writeWorldPrompt(world.directory, tag, id, withPlayer(body));
779
+ const carriesSampling = Object.keys(preset.sampling).length > 0;
780
+ if (carriesSampling) {
781
+ await editWorldInfo(world.directory, { sampling: preset.sampling });
782
+ await worlds.list({ refresh: true });
783
+ }
642
784
  await rm(file, { force: true });
643
785
  const written = made.prompts.map((entry) => entry.id);
644
786
  return JSON.parse(JSON.stringify({
645
787
  preset: preset.name,
646
788
  written,
789
+ sampling: carriesSampling ? preset.sampling : void 0,
647
790
  folder: `${PROMPTS_FOLDER}/<language>/`,
648
791
  notes: made.notes,
649
- next: written.length === 0 ? "Nothing in the preset was about how to write the story, so no prompt was changed: tell the person." : "Tell the person which prompts were written (they can read and edit them in the world's Prompts section) and what was not carried over."
792
+ next: written.length === 0 ? "Nothing in the preset was about how to write the story, so no prompt was changed: tell the person." : "Tell the person which prompts were written (they can read and edit them in the world's Prompts section), the sampling that was set (About section) and what was not carried over."
650
793
  }));
651
794
  }
652
795
  })];
@@ -1077,6 +1220,8 @@ async function readWorldEditor(world) {
1077
1220
  key: entry.id,
1078
1221
  title: entry.title,
1079
1222
  kind: entry.kind,
1223
+ scope: entry.scope,
1224
+ knownBy: entry.knownBy,
1080
1225
  summary: entry.summary,
1081
1226
  body: entry.body,
1082
1227
  ...entry.startsAt === void 0 ? {} : { startsAt: entry.startsAt },
@@ -1122,9 +1267,22 @@ async function editWorldPlots(world, edit) {
1122
1267
  return await readWorldEditor(world);
1123
1268
  }
1124
1269
  async function editWorldLore(world, key, edit) {
1270
+ if (edit.knownBy !== void 0) {
1271
+ const { characters } = await loadCharacters(world.directory);
1272
+ const strangers = edit.knownBy.filter((name) => !knowsCharacter(characters, name));
1273
+ if (strangers.length > 0) throw new InvalidEditProblems(strangers.map((name) => `"${name}" is not a character of this world`));
1274
+ }
1125
1275
  return await editEntityFile(world, LORE_DIR, LORE_FILE_NAME, key, parseLoreFile, (document) => {
1126
1276
  if (edit.title !== void 0) document["title"] = edit.title;
1127
1277
  if (edit.kind !== void 0) document["kind"] = edit.kind;
1278
+ if (edit.scope !== void 0) {
1279
+ document["scope"] = edit.scope;
1280
+ if (edit.scope === "everyone" && edit.knownBy === void 0) delete document["known_by"];
1281
+ }
1282
+ if (edit.knownBy !== void 0) {
1283
+ if (edit.knownBy.length === 0) delete document["known_by"];
1284
+ else document["known_by"] = edit.knownBy;
1285
+ }
1128
1286
  if (edit.summary !== void 0) setOptional(document, "summary", edit.summary);
1129
1287
  if (edit.body !== void 0) setOptional(document, "body", edit.body);
1130
1288
  if (edit.sources !== void 0) document["sources"] = edit.sources;
@@ -1974,6 +2132,6 @@ function registerPackJail(ctx, deps) {
1974
2132
  ctx.on("tools/pre-execute", (exec, next) => packJail(exec, next, deps), { prepend: true });
1975
2133
  }
1976
2134
  //#endregion
1977
- export { worldEntityImageFile as A, translateTools as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile$1 as E, loadWorldParts as F, readWorldDocuments as H, PRESET_FILE as I, presetMessage as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, presetTools as R, generateWorldEntityImage as S, removeWorldTrigger as T, languageOfDocuments as V, editWorldPlots as _, deleteWorldPackFile as a, entityFolder as b, createAuthoredEntity as c, replaceAuthoredEntity as d, editWorldCharacter as f, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, editWorldLore as m, packFileProblem as n, listWorldPacks as o, editWorldFaction as p, registerPackJail as r, AUTHORED_ENTITY_KINDS as s, MAX_PACK_TEXT as t, readAuthoredEntityDocument as u, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, translateMessage as z };
2135
+ export { worldEntityImageFile as A, readWorldInfo as B, readWorldEditor as C, uploadWorldCharacterPortrait as D, replaceFile$1 as E, loadWorldParts as F, translateTools as H, PRESET_FILE as I, presetMessage as L, deleteTriggerDocument as M, readTriggerDocuments as N, uploadWorldEntityImage as O, writeTriggerDocument as P, presetTools as R, generateWorldEntityImage as S, removeWorldTrigger as T, languageOfDocuments as U, translateMessage as V, readWorldDocuments as W, editWorldPlots as _, deleteWorldPackFile as a, entityFolder as b, createAuthoredEntity as c, replaceAuthoredEntity as d, editWorldCharacter as f, editWorldPlace as g, editWorldNarrationVoice as h, checkWorldPack as i, writeWorldTrigger as j, worldCharacterPortraitFile as k, deleteAuthoredEntity as l, editWorldLore as m, packFileProblem as n, listWorldPacks as o, editWorldFaction as p, registerPackJail as r, AUTHORED_ENTITY_KINDS as s, MAX_PACK_TEXT as t, readAuthoredEntityDocument as u, editWorldRelation as v, readWorldTrigger as w, generateWorldCharacterPortrait as x, editWorldThing as y, editWorldInfo as z };
1978
2136
 
1979
- //# sourceMappingURL=pack-jail-ClMpVc__.js.map
2137
+ //# sourceMappingURL=pack-jail-soI-In96.js.map