@dsh-agentic-roleplay/core 0.11.0 → 0.12.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 (62) hide show
  1. package/lib/{access-CXtaZNbx.js → access-DAw54-NI.js} +6 -15
  2. package/lib/{authoring-tools--6V1pIIL.js → authoring-tools-4NgDhIJV.js} +116 -13
  3. package/lib/authoring.js +38 -8
  4. package/lib/{child-C9nPIy9j.js → child-D3QUNb3m.js} +121 -2
  5. package/lib/client.js +1389 -475
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +3 -3
  8. package/lib/doctor.js +3 -3
  9. package/lib/{gallery-CtG-bDzz.js → gallery-Ct6nm4UQ.js} +3 -3
  10. package/lib/{generator-nLoPM5MF.js → generator-CI8fOnXy.js} +9 -3
  11. package/lib/helper.js +22 -1
  12. package/lib/{hooks-DORky4KT.js → hooks-BNeoGMHZ.js} +1342 -293
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +444 -24
  15. package/lib/jail-BIF79PJO.js +107 -0
  16. package/lib/{library-CH-ahlm0.js → library-BF9ZMSFz.js} +3 -3
  17. package/lib/{lorebook-author-tools-BrVde1N-.js → lorebook-author-tools-DBk-V0hp.js} +7 -7
  18. package/lib/lorebook-authoring.js +4 -4
  19. package/lib/{narration-B0hConSw.js → narration-xvErE2yp.js} +34 -3
  20. package/lib/orchestration.js +915 -59
  21. package/lib/{pack-jail-Bk82pX9t.js → pack-jail-C8EyX9Ix.js} +18 -14
  22. package/lib/{packs-ELfh8yh1.js → packs-S0SzrVv-.js} +2 -2
  23. package/lib/{presenter-agent-UKbKYXMO.js → presenter-agent-Bc478nTA.js} +11 -8
  24. package/lib/{preset-D9Sfc8sf.js → preset-SJZyw0kt.js} +4 -4
  25. package/lib/{preset-author-tools-B3pFL1-e.js → preset-author-tools-CzogjK42.js} +7 -7
  26. package/lib/preset-authoring.js +5 -5
  27. package/lib/{presets-BRt4Xsy4.js → presets-DQ5rioMh.js} +251 -49
  28. package/lib/{reflection-CHiHsY4Y.js → reflection-buQiSdvq.js} +17 -609
  29. package/lib/service-mRKwpWjX.js +140 -0
  30. package/lib/{text-CzqhC8sT.js → text-Dfv8S8eq.js} +36 -2
  31. package/lib/{turn-guard-B53qOWEU.js → turn-guard-BSAba8sp.js} +3 -3
  32. package/package.json +3 -3
  33. package/prompts/en/import/finish-ok.md +1 -1
  34. package/prompts/en/import/generator.md +1 -1
  35. package/prompts/en/import/style.md +1 -1
  36. package/prompts/en/import/variables.md +3 -1
  37. package/prompts/en/roleplay/character-decide.md +1 -1
  38. package/prompts/en/roleplay/character-lookup.md +1 -1
  39. package/prompts/en/roleplay/decide-errand.md +1 -0
  40. package/prompts/en/roleplay/decide-message.md +1 -0
  41. package/prompts/en/roleplay/decide-reuse.md +3 -0
  42. package/prompts/en/roleplay/decide-variable.md +1 -0
  43. package/prompts/en/roleplay/dream.md +1 -0
  44. package/prompts/en/roleplay/gate-repeat.md +1 -0
  45. package/prompts/en/roleplay/image-presenter.md +1 -0
  46. package/prompts/en/roleplay/track-values.md +1 -0
  47. package/prompts/en/roleplay/track-variables.md +1 -0
  48. package/prompts/zh/import/finish-ok.md +1 -1
  49. package/prompts/zh/import/generator.md +1 -1
  50. package/prompts/zh/import/style.md +1 -1
  51. package/prompts/zh/import/variables.md +3 -1
  52. package/prompts/zh/roleplay/character-decide.md +1 -1
  53. package/prompts/zh/roleplay/character-lookup.md +1 -1
  54. package/prompts/zh/roleplay/decide-errand.md +1 -0
  55. package/prompts/zh/roleplay/decide-message.md +1 -0
  56. package/prompts/zh/roleplay/decide-reuse.md +3 -0
  57. package/prompts/zh/roleplay/decide-variable.md +1 -0
  58. package/prompts/zh/roleplay/dream.md +1 -0
  59. package/prompts/zh/roleplay/gate-repeat.md +1 -0
  60. package/prompts/zh/roleplay/image-presenter.md +1 -0
  61. package/prompts/zh/roleplay/track-values.md +1 -0
  62. package/prompts/zh/roleplay/track-variables.md +1 -0
@@ -1,20 +1,8 @@
1
+ import { j as roleplaySessionOf } from "./child-D3QUNb3m.js";
1
2
  import { basename, dirname, join } from "node:path";
2
3
  import { chmodSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { chmod, mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
5
- // src/shared/chat.ts
6
- const CHAT_PREFIX = "session-";
7
- const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
8
- /** The DSH chat of a roleplay session is named after the session's id. */
9
- function chatSessionId(sessionId) {
10
- return `${CHAT_PREFIX}${sessionId}`;
11
- }
12
- /** The roleplay session a DSH chat id could belong to; ordinary DSH chats have ids of the same shape. */
13
- function roleplaySessionOf(chat) {
14
- if (!chat.startsWith(CHAT_PREFIX)) return void 0;
15
- const id = chat.slice(8);
16
- return UUID_V4.test(id) ? id : void 0;
17
- }
18
6
  // ../dsh-roleplay-model/src/variable.ts
19
7
  /** What a variable holds: a number within bounds, a yes or no, or one of a list of words. */
20
8
  const VARIABLE_KINDS = [
@@ -42,6 +30,7 @@ const VARIABLE_VISIBILITIES = [
42
30
  {
43
31
  key: "valence",
44
32
  name: "Valence",
33
+ update: "",
45
34
  description: "How pleasant its mood is: -1 very unpleasant, 0 neutral, 1 very pleasant.",
46
35
  labels: [
47
36
  {
@@ -69,6 +58,7 @@ const VARIABLE_VISIBILITIES = [
69
58
  {
70
59
  key: "arousal",
71
60
  name: "Arousal",
61
+ update: "",
72
62
  description: "How worked up it is: -1 drowsy, 0 ordinary, 1 frantic.",
73
63
  labels: [
74
64
  {
@@ -96,6 +86,7 @@ const VARIABLE_VISIBILITIES = [
96
86
  {
97
87
  key: "dominance",
98
88
  name: "Dominance",
89
+ update: "",
99
90
  description: "How much in control it feels: -1 helpless, 0 even, 1 commanding.",
100
91
  labels: [
101
92
  {
@@ -190,6 +181,6 @@ function promptFor(agent, id, language, variables) {
190
181
  if (library === void 0) throw new Error("the prompt library is not running");
191
182
  return library.text(id, language, variables, roleplaySessionOf(agent.session.id));
192
183
  }
193
- export { VARIABLE_KINDS as a, chatSessionId as c, atomicWriteSync as i, roleplaySessionOf as l, atomicWrite as n, VARIABLE_SUBJECTS as o, atomicWriteJson as r, VARIABLE_VISIBILITIES as s, promptFor as t };
184
+ export { VARIABLE_KINDS as a, atomicWriteSync as i, atomicWrite as n, VARIABLE_SUBJECTS as o, atomicWriteJson as r, VARIABLE_VISIBILITIES as s, promptFor as t };
194
185
 
195
- //# sourceMappingURL=access-CXtaZNbx.js.map
186
+ //# sourceMappingURL=access-DAw54-NI.js.map
@@ -1,10 +1,10 @@
1
- import { n as atomicWrite, r as atomicWriteJson } from "./access-CXtaZNbx.js";
2
- import { $ as IMPORT_FOLDER, A as sourcesFor, At as InvalidEditProblems, Bt as DEFAULT_SLOTS, C as inert, Ct as parseSlotsFile, D as pruneLoreSubjects, Dt as parseCharacterFile, E as pruneLinks, Et as CHARACTER_FILE_NAME, F as ROLE_TABLE, I as isLeftOut, Lt as LORE_KINDS, M as classifyItems, N as findEntity, O as pruneMembers, Ot as readVariableValues, P as ROLES, Q as withPlayer, R as askYesNo, Rt as LORE_SCOPES, S as extractVariables, St as parseItemFile, T as pruneKnowledge, Tt as parseFactionFile, U as yesAt, V as noAt, X as itemise, Y as cleanText, _ as characterDocument, _t as parseLoreFile, a as isPresetName, at as readImportFolder, b as extractStyle, bt as ITEM_FILE_NAME, ft as VARIABLES_FILE_NAME, g as asWritten, gt as LORE_FILE_NAME, h as addLore, ht as variableProblems, j as buildRoster, k as pruneRelationships, kt as readIdentifier, nt as PICTURE_FILE, pt as loadVariables, rt as openingText, st as dialectOf, ut as parseImportCommand, v as emptyExtracted, vt as LOCATION_FILE_NAME, w as loreDocuments, wt as FACTION_FILE_NAME, xt as SLOTS_FILE_NAME, y as extractEntities, yt as parseLocationFile, zt as WEEKDAY_NAMES } from "./presets-BRt4Xsy4.js";
3
- import { f as parseSwitchboard } from "./narration-B0hConSw.js";
4
- import { $ as listFiles, G as formatIssue, J as PROMPTS_FOLDER, K as errorMessage, L as loadPlots, U as readDocument$1, V as commandFlagKey, W as Reader, X as copyWorldPrompts, a as externalWithheld, et as promptProblem, gt as COMPARISONS, ot as InvalidWorldError, r as externalGiven, rt as shippedText, t as externalToolLimit, tt as shippedLanguages, z as plotReferenceProblems } from "./hooks-DORky4KT.js";
5
- import { t as trimCharacters } from "./text-CzqhC8sT.js";
6
- import { S as currentTurn, c as namedModel, d as parseSampling, l as runChild, t as ChildTimeoutError } from "./child-C9nPIy9j.js";
7
- import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-CH-ahlm0.js";
1
+ import { T as currentTurn, c as namedModel, l as runChild, m as parseSampling, t as ChildTimeoutError } from "./child-D3QUNb3m.js";
2
+ import { $ as IMPORT_FOLDER, A as sourcesFor, At as readVariableValues, Bt as LORE_KINDS, C as inert, Ct as SLOTS_FILE_NAME, D as pruneLoreSubjects, Dt as parseFactionFile, E as pruneLinks, Et as FACTION_FILE_NAME, F as ROLE_TABLE, Ht as WEEKDAY_NAMES, I as isLeftOut, M as classifyItems, Mt as InvalidEditProblems, N as findEntity, O as pruneMembers, Ot as CHARACTER_FILE_NAME, P as ROLES, Q as withPlayer, R as askYesNo, S as extractVariables, St as ITEM_FILE_NAME, T as pruneKnowledge, Tt as parseSlotsFile, U as yesAt, Ut as DEFAULT_SLOTS, V as noAt, Vt as LORE_SCOPES, X as itemise, Y as cleanText, _ as characterDocument, _t as variableProblems, a as isPresetName, at as readImportFolder, b as extractStyle, bt as LOCATION_FILE_NAME, ct as parseImportCommand, dt as splitPanels, ft as dialectOf, g as asWritten, h as addLore, ht as loadVariables, j as buildRoster, jt as readIdentifier, k as pruneRelationships, kt as parseCharacterFile, mt as VARIABLES_FILE_NAME, nt as PICTURE_FILE, rt as openingText, ut as findPanel, v as emptyExtracted, vt as LORE_FILE_NAME, w as loreDocuments, wt as parseItemFile, xt as parseLocationFile, y as extractEntities, yt as parseLoreFile, zt as guarded } from "./presets-DQ5rioMh.js";
3
+ import { f as parseSwitchboard } from "./narration-xvErE2yp.js";
4
+ import { n as atomicWrite, r as atomicWriteJson } from "./access-DAw54-NI.js";
5
+ import { G as readDocument$1, J as errorMessage, K as Reader, Q as copyWorldPrompts, U as commandFlagKey, V as plotReferenceProblems, X as PROMPTS_FOLDER, _t as COMPARISONS, a as externalGiven, at as shippedText, ct as InvalidWorldError, nt as promptProblem, q as formatIssue, rt as shippedLanguages, s as externalWithheld, t as externalToolLimit, tt as listFiles, z as loadPlots } from "./hooks-BNeoGMHZ.js";
6
+ import { t as trimCharacters } from "./text-Dfv8S8eq.js";
7
+ import { C as slug, S as norm, T as uniqueKey, _ as writeImageFileMetadata, b as NoEmbeddingService, i as libraryHashes, n as addToLibraryOnce, p as MEDIA_TYPES, r as imageExtensionOf, u as referenceImagePath, w as trOf, x as mapLimit } from "./library-BF9ZMSFz.js";
8
8
  import { dirname, join, relative } from "node:path";
9
9
  import { MINUTE, MONTH_NAMES, SEASONS, checkProblems, createSessionStore, dayTokenProblems, isTimeZone, lintWorld, parseInstant, parseTimeOfDay, readTriggerDefinition, triggerReferenceProblems, writeCalendar } from "@dsh-agentic-roleplay/state";
10
10
  import { existsSync, readFileSync } from "node:fs";
@@ -1118,6 +1118,7 @@ function populateRoutines(session, characters) {
1118
1118
  end: parseTimeOfDay(window.to),
1119
1119
  activity: window.activity,
1120
1120
  interruptible: window.interruptible,
1121
+ ...window.sleep === true ? { sleep: true } : {},
1121
1122
  ...window.location === void 0 ? {} : { locationId: session.locations.getBySourceId(window.location).id },
1122
1123
  ...window.feature === void 0 ? {} : { featureKey: window.feature },
1123
1124
  ...window.position === void 0 ? {} : { position: window.position }
@@ -2145,7 +2146,7 @@ function parseWorldInfoEdit(value) {
2145
2146
  const input = typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2146
2147
  if (input === void 0) throw new InvalidEditProblems(["the changes must be an object"]);
2147
2148
  const edit = {};
2148
- for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "startQuestions" && key !== "tools" && key !== "sampling") problems.push(`there is no field "${key}"`);
2149
+ for (const key of Object.keys(input)) if (!TEXT_FIELDS.includes(key) && !LIST_FIELDS.includes(key) && key !== "alternateOpenings" && key !== "startQuestions" && key !== "tools" && key !== "sampling" && key !== "autonomy") problems.push(`there is no field "${key}"`);
2149
2150
  for (const key of TEXT_FIELDS) {
2150
2151
  if (input[key] === void 0) continue;
2151
2152
  if (typeof input[key] === "string") edit[key] = input[key].trim();
@@ -2180,6 +2181,10 @@ function parseWorldInfoEdit(value) {
2180
2181
  if (typeof board === "string") problems.push(board);
2181
2182
  else edit["tools"] = board;
2182
2183
  }
2184
+ if (input["autonomy"] !== void 0) {
2185
+ if (typeof input["autonomy"] === "boolean") edit["autonomy"] = input["autonomy"];
2186
+ else problems.push("autonomy must be true or false");
2187
+ }
2183
2188
  if (input["sampling"] !== void 0) edit["sampling"] = parseSampling(input["sampling"], "sampling", problems);
2184
2189
  if (typeof edit["version"] === "string" && edit["version"].length > 40) problems.push(`the version is longer than 40 characters`);
2185
2190
  if (edit["name"] === "") problems.push("the world needs a name");
@@ -2426,6 +2431,9 @@ function parseWorldFile(text) {
2426
2431
  const variables = readVariableValues(reader);
2427
2432
  const rules = readRules(reader);
2428
2433
  const tools = readTools(reader);
2434
+ const autonomyValue = reader.raw("autonomy");
2435
+ if (autonomyValue !== void 0 && autonomyValue !== null && typeof autonomyValue !== "boolean") reader.fail("autonomy", "must be true or false");
2436
+ const autonomy = autonomyValue === true ? true : void 0;
2429
2437
  const alternateOpenings = readAlternateOpenings(reader);
2430
2438
  const startQuestions = readStartQuestions(reader, alternateOpenings?.length ?? 0);
2431
2439
  const narrationVoice = reader.string("narration_voice")?.trim() || void 0;
@@ -2453,6 +2461,7 @@ function parseWorldFile(text) {
2453
2461
  ...variables === void 0 ? {} : { variables },
2454
2462
  ...rules === void 0 ? {} : { rules },
2455
2463
  ...tools === void 0 ? {} : { tools },
2464
+ ...autonomy === void 0 ? {} : { autonomy },
2456
2465
  ...alternateOpenings === void 0 ? {} : { alternateOpenings },
2457
2466
  ...startQuestions === void 0 ? {} : { startQuestions },
2458
2467
  ...narrationVoice === void 0 ? {} : { narrationVoice },
@@ -3110,7 +3119,7 @@ async function writePortrait(directory, picture, characters, cardName) {
3110
3119
  }
3111
3120
  /** The card's opening as the world's opening message: plain paragraphs, without the markup the card's tool read as emphasis. */
3112
3121
  function openingMessage(raw, cardName, player) {
3113
- const text = cleanText(raw, cardName).replace(/<\/?[a-z][^>\n]*>/gi, "").replace(/```[a-z]*\n?|```/g, "").replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/(^|[^*])\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)/g, "$1$2").replace(/\n{3,}/g, "\n\n").trim();
3122
+ const text = cleanText(splitPanels(raw).prose, cardName).replace(/<\/?[a-z][^>\n]*>/gi, "").replace(/```[a-z]*\n?|```/g, "").replace(/\*\*([^*\n]+)\*\*/g, "$1").replace(/(^|[^*])\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)/g, "$1$2").replace(/\n{3,}/g, "\n\n").trim();
3114
3123
  return withPlayer(text, player);
3115
3124
  }
3116
3125
  /** Every player marker in the strings of a value, replaced by the player's character or a plain word for the player; the value is changed in place. */
@@ -4138,6 +4147,7 @@ function infoOf(document, startQuestions = []) {
4138
4147
  version: typeof document["version"] === "number" ? String(document["version"]) : textOf(document["version"]),
4139
4148
  sampling: parseSampling(document["sampling"], "sampling", []),
4140
4149
  tools: toolsOf(document["tools"]),
4150
+ autonomy: document["autonomy"] === true,
4141
4151
  startQuestions,
4142
4152
  alternateOpenings: Array.isArray(document["alternate_openings"]) ? document["alternate_openings"].flatMap((entry) => typeof entry === "object" && entry !== null && typeof entry["text"] === "string" ? [{
4143
4153
  title: textOf(entry["title"]),
@@ -4225,6 +4235,10 @@ async function changeWorldInfo(directory, edit) {
4225
4235
  if (Object.keys(edit.sampling).length === 0) delete document["sampling"];
4226
4236
  else document["sampling"] = edit.sampling;
4227
4237
  }
4238
+ if (edit.autonomy !== void 0) {
4239
+ if (edit.autonomy) document["autonomy"] = true;
4240
+ else delete document["autonomy"];
4241
+ }
4228
4242
  if (edit.tools !== void 0) {
4229
4243
  if (Object.keys(edit.tools).length === 0) delete document["tools"];
4230
4244
  else document["tools"] = edit.tools;
@@ -4551,6 +4565,67 @@ const names$1 = {
4551
4565
  return foundBy("name-clashes", found);
4552
4566
  }
4553
4567
  };
4568
+ const NUMERALS = /[\p{N}一二三四五六七八九十零〇两百千]/u;
4569
+ /** Whether two names differ in exactly one place: a letter changed, added, left out, or two neighbours swapped. A difference in a number (Room 3, Room 4) is a pattern, not a slip. */
4570
+ function oneApart(a, b) {
4571
+ const x = [...a];
4572
+ const y = [...b];
4573
+ if (Math.abs(x.length - y.length) > 1 || a === b) return false;
4574
+ let start = 0;
4575
+ while (start < x.length && start < y.length && x[start] === y[start]) start += 1;
4576
+ let endX = x.length;
4577
+ let endY = y.length;
4578
+ while (endX > start && endY > start && x[endX - 1] === y[endY - 1]) {
4579
+ endX -= 1;
4580
+ endY -= 1;
4581
+ }
4582
+ const left = x.slice(start, endX);
4583
+ const right = y.slice(start, endY);
4584
+ const swapped = left.length === 2 && right.length === 2 && left[0] === right[1] && left[1] === right[0];
4585
+ if (!(left.length <= 1 && right.length <= 1) && !swapped) return false;
4586
+ return ![...left, ...right].some((char) => NUMERALS.test(char));
4587
+ }
4588
+ /** The shortest name that is compared: a very short one differs from many others by one letter. */
4589
+ const MIN_CONFUSABLE = 4;
4590
+ const confusable = {
4591
+ id: "name-confusable",
4592
+ kit: "consistency",
4593
+ mode: "code",
4594
+ needs: [],
4595
+ description: "Two characters, places or organisations whose names differ by one letter (Mara and Mira): readers and the models mix them up, though they are two. Numbered names (Room 3, Room 4) are not reported.",
4596
+ async run(input) {
4597
+ const [{ characters }, { locations }, { factions }] = await Promise.all([
4598
+ loaded.characters(input),
4599
+ loaded.locations(input),
4600
+ loaded.factions(input)
4601
+ ]);
4602
+ const kinds = [
4603
+ ["characters", characters],
4604
+ ["locations", locations],
4605
+ ["factions", factions]
4606
+ ];
4607
+ const found = [];
4608
+ for (const [kind, entries] of kinds) {
4609
+ const names = entries.map((entry) => ({
4610
+ id: entry.id,
4611
+ name: norm(entry.name)
4612
+ })).filter((entry) => [...entry.name].length >= (/[\u3400-\u9fff]/u.test(entry.name) ? 2 : MIN_CONFUSABLE));
4613
+ for (let a = 0; a < names.length; a++) for (let b = a + 1; b < names.length; b++) {
4614
+ if (!oneApart(names[a].name, names[b].name)) continue;
4615
+ const first = entries.find((entry) => entry.id === names[a].id);
4616
+ const second = entries.find((entry) => entry.id === names[b].id);
4617
+ found.push({
4618
+ severity: "info",
4619
+ code: "confusable-names",
4620
+ where: `${kind}/${second.id}`,
4621
+ message: `${kind}/${first.id} ("${first.name}") and ${kind}/${second.id} ("${second.name}") differ by one letter, so they are easy to mix up`,
4622
+ hint: "If they are two, give one a clearly different name; if they are one, keep one and point everything that names the other at it."
4623
+ });
4624
+ }
4625
+ }
4626
+ return foundBy("name-confusable", found);
4627
+ }
4628
+ };
4554
4629
  const prompts = {
4555
4630
  id: "world-prompts",
4556
4631
  kit: "consistency",
@@ -4586,6 +4661,7 @@ const consistencyChecks = [
4586
4661
  graph,
4587
4662
  values,
4588
4663
  names$1,
4664
+ confusable,
4589
4665
  prompts,
4590
4666
  {
4591
4667
  id: "unread-fields",
@@ -4775,7 +4851,7 @@ function worldFieldChanges(before, after) {
4775
4851
  field: "authorName",
4776
4852
  because: `the card\'s creator is now “${after.card.creator}”`
4777
4853
  });
4778
- if (differ(openingText(before.card, before.choices.opening) ?? "", openingText(after.card, after.choices.opening) ?? "")) changes.push({
4854
+ if (differ(splitPanels(openingText(before.card, before.choices.opening) ?? "").prose, splitPanels(openingText(after.card, after.choices.opening) ?? "").prose)) changes.push({
4779
4855
  field: "opening",
4780
4856
  because: "the greeting the world opens with changed; suggested is the new greeting as the import writes an opening (plain paragraphs, the card's markup removed, the player named by the world's player character where the card says {{user}})",
4781
4857
  suggested: openingMessage(openingText(after.card, after.choices.opening) ?? "", after.card.name)
@@ -5919,6 +5995,31 @@ const about = {
5919
5995
  return foundBy("quality-world", found);
5920
5996
  }
5921
5997
  };
5998
+ const PANEL_QUOTE_CHARS = 120;
5999
+ const panels = {
6000
+ id: "quality-panels",
6001
+ kit: "quality",
6002
+ mode: "code",
6003
+ needs: [],
6004
+ description: "Status bars, panels and update blocks written into the opening, the prompts, the lore or the characters: a story shows its tracked values itself, and a game master that is told to print one writes it into the narration.",
6005
+ async run(input) {
6006
+ const { texts } = await loaded.text(input);
6007
+ const found = [];
6008
+ for (const [where, body] of texts) {
6009
+ const panel = findPanel(body);
6010
+ if (panel === void 0) continue;
6011
+ const quote = panel.replace(/\s+/g, " ").slice(0, PANEL_QUOTE_CHARS);
6012
+ found.push({
6013
+ severity: "warning",
6014
+ code: "output-panel",
6015
+ where,
6016
+ message: `${where} holds a status bar or markup a story would print: ${quote}`,
6017
+ hint: "Take it out with the editing tools; keeping it is never intended. Declare the values it shows in variables.json (the story shows them) and do not keep the layout or an instruction to print it."
6018
+ });
6019
+ }
6020
+ return foundBy("quality-panels", found);
6021
+ }
6022
+ };
5922
6023
  const SHEET_SCHEMA = {
5923
6024
  type: "object",
5924
6025
  properties: {
@@ -5997,6 +6098,7 @@ const qualityChecks = [
5997
6098
  cast,
5998
6099
  places,
5999
6100
  about,
6101
+ panels,
6000
6102
  sheets,
6001
6103
  {
6002
6104
  id: "world-gaps",
@@ -6523,6 +6625,7 @@ async function forgetJobs(directory) {
6523
6625
  });
6524
6626
  }
6525
6627
  // src/host/import/tools.ts
6628
+ const residencyOf = (agent) => agent.ctx.get("roleplayOrchestration")?.residency;
6526
6629
  const SURVEY_TOOL = "import_survey";
6527
6630
  const BUILD_TOOL = "import_build";
6528
6631
  const FINISH_TOOL = "import_finish";
@@ -6607,12 +6710,12 @@ function contextOf(exec, settings, text, language, keepIn) {
6607
6710
  };
6608
6711
  const run = keepIn === void 0 ? ask : cachedJobs(keepIn, ask);
6609
6712
  const decide = settings.decisions === "decision" ? (state, asks) => {
6610
- const service = agent.ctx.get("decisions");
6713
+ const service = guarded(residencyOf(agent), "decision", agent.ctx.get("decisions"), ["decide"]);
6611
6714
  if (service === void 0) return Promise.reject(/* @__PURE__ */ new Error("no decision service is selected, or the selected one is not loaded"));
6612
6715
  return askYesNo(service, state, asks, exec.signal);
6613
6716
  } : void 0;
6614
6717
  const embed = async (texts) => {
6615
- const service = agent.ctx.get("embeddings");
6718
+ const service = guarded(residencyOf(agent), "embedding", agent.ctx.get("embeddings"), ["embed"]);
6616
6719
  if (service === void 0) throw new NoEmbeddingService("no embedding provider is selected, or the selected one is not loaded");
6617
6720
  const { vectors, model } = await service.embed(texts, {
6618
6721
  inputType: "document",
@@ -6866,4 +6969,4 @@ function limitAuthoringAgents(ctx, kindOf) {
6866
6969
  }
6867
6970
  export { readSource as $, subfolders as $t, editsSince as A, populateLore as At, addressesToFetch as B, loadLocations as Bt, worldFieldChanges as C, populateCharacters as Ct, loadCardEvidence as D, populateItems as Dt, loadWorldParts as E, populateFactions as Et, localChanges as F, TRIGGERS_FILE_NAME as Ft, vetUrl as G, DICE_FILE_NAME as Gt, fetchPictures as H, loadItems as Ht, readOrigin as I, loadTriggers as It, UPDATE_FOLDER as J, CALENDAR_FILE_NAME as Jt, cardCharacter as K, loadDice as Kt, writeOrigin as L, LORE_DIR as Lt, describeChanges as M, populateTriggers as Mt, hashWorld as N, populateVariables as Nt, CHECK_COMMANDS as O, populateKnowledge as Ot, isUnchanged as P, routineProblems as Pt, entitiesByPiece as Q, loadCharacters as Qt, CatalogueError as R, loadLore as Rt, pictureChange as S, populateCalendar as St, readWorldInfo as T, populateDice as Tt, guardedLookup as U, FACTIONS_DIR as Ut, candidateUrls as V, ITEMS_DIR as Vt, mergeReports as W, loadFactions as Wt, cardPieces as X, parseCalendarFile as Xt, baseId as Y, loadCalendar as Yt, cardTools as Z, CHARACTERS_DIR as Zt, runChecks as _, writeLorebookEntry as _t, importHooks as a, readCard as an, addLorebookEntries as at, diffText as b, withScratchStory as bt, importPhase as c, DICE_RESULTS as cn, deleteLorebookEntry as ct, markReady as d, listLorebooks as dt, knownOutputCeiling as en, WORLD_FILE_NAME as et, settleDraft as f, loadLorebook as ft, CHECKS as g, updateLorebookInfo as gt, presentReport as h, reserveLorebook as ht, contextOf as i, pictureOf as in, questionView as it, writeSnapshot as j, populateRoutines as jt, recordProvenance as k, populateLocations as kt, isReviewing as l, authoredWorldOf as ln, entriesOf as lt, checkImported as m, readLorebook as mt, limitAuthoringAgents as n, cardFormat as nn, parseWorldInfoEdit as nt, importTools as o, DICE_COMPARISONS as on, createLorebook as ot, structureImport as p, lorebookDirectory as pt, writePortrait as q, parseDiceFile as qt, MAX_PREVIEW_TEXT as r, isPng as rn, combineAnswers as rt, worldOf as s, DICE_READINGS as sn, deleteLorebook as st, AuthoringTools as t, ImportCardError as tn, parseWorldFile as tt, keepDraft as u, authoringChatSessionId as un, isLorebookName as ut, addressChanges as v, checkWorld as vt, editWorldInfo as w, populateClock as wt, matchPieces as x, knowsCharacter as xt, cardChanges as y, loadValidatedWorld as yt, addressKey as z, LOCATIONS_DIR as zt };
6868
6971
 
6869
- //# sourceMappingURL=authoring-tools--6V1pIIL.js.map
6972
+ //# sourceMappingURL=authoring-tools-4NgDhIJV.js.map
package/lib/authoring.js CHANGED
@@ -1,11 +1,11 @@
1
- import { $ as readSource, A as editsSince, C as worldFieldChanges, D as loadCardEvidence, E as loadWorldParts, J as UPDATE_FOLDER, O as CHECK_COMMANDS, Q as entitiesByPiece, S as pictureChange, T as readWorldInfo, Z as cardTools, _ as runChecks, a as importHooks, b as diffText, g as CHECKS, h as presentReport, i as contextOf, l as isReviewing, ln as authoredWorldOf, m as checkImported, n as limitAuthoringAgents, nt as parseWorldInfoEdit, o as importTools, v as addressChanges, vt as checkWorld, w as editWorldInfo, x as matchPieces, y as cardChanges } from "./authoring-tools--6V1pIIL.js";
2
- import { t as guardAuthoringTurns } from "./turn-guard-B53qOWEU.js";
3
- import { C as readWorldEditor, L as presetTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, U as finishUpdate, W as pendingUpdate, _ 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, z as translateTools } from "./pack-jail-Bk82pX9t.js";
4
- import { $ as IMPORT_FOLDER, At as InvalidEditProblems, Ft as parseRelationEdit, G as deleteWorldPrompt, J as writeWorldPrompt, K as listWorldPrompts, W as PROSE_PROMPTS, dt as parseAuthoringCommand, nt as PICTURE_FILE, q as readWorldPrompt } from "./presets-BRt4Xsy4.js";
5
- import { i as translator, r as languageOf } from "./text-CzqhC8sT.js";
6
- import { G as formatIssue, R as parsePlotsFile, nt as shippedPromptsDirectory } from "./hooks-DORky4KT.js";
7
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-ELfh8yh1.js";
8
- import "./access-CXtaZNbx.js";
1
+ import { $ as readSource, A as editsSince, C as worldFieldChanges, D as loadCardEvidence, E as loadWorldParts, J as UPDATE_FOLDER, O as CHECK_COMMANDS, Q as entitiesByPiece, S as pictureChange, T as readWorldInfo, Z as cardTools, _ as runChecks, a as importHooks, b as diffText, g as CHECKS, h as presentReport, i as contextOf, l as isReviewing, ln as authoredWorldOf, m as checkImported, n as limitAuthoringAgents, nt as parseWorldInfoEdit, o as importTools, v as addressChanges, vt as checkWorld, w as editWorldInfo, x as matchPieces, y as cardChanges } from "./authoring-tools-4NgDhIJV.js";
2
+ import { t as guardAuthoringTurns } from "./turn-guard-BSAba8sp.js";
3
+ import { C as readWorldEditor, L as presetTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, U as finishUpdate, W as pendingUpdate, _ 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, z as translateTools } from "./pack-jail-C8EyX9Ix.js";
4
+ import { $ as IMPORT_FOLDER, G as deleteWorldPrompt, J as writeWorldPrompt, K as listWorldPrompts, Lt as parseRelationEdit, Mt as InvalidEditProblems, W as PROSE_PROMPTS, lt as parseAuthoringCommand, nt as PICTURE_FILE, q as readWorldPrompt } from "./presets-DQ5rioMh.js";
5
+ import { i as translator, r as languageOf } from "./text-Dfv8S8eq.js";
6
+ import { B as parsePlotsFile, it as shippedPromptsDirectory, q as formatIssue } from "./hooks-BNeoGMHZ.js";
7
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-S0SzrVv-.js";
8
+ import "./access-DAw54-NI.js";
9
9
  import { join, relative } from "node:path";
10
10
  import { createHash } from "node:crypto";
11
11
  import { readFile, readdir } from "node:fs/promises";
@@ -589,6 +589,25 @@ function plotDocument(value) {
589
589
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
590
590
  return parsed.value[0];
591
591
  }
592
+ /** Checks a write the way its tool will, and writes nothing: a change the tool would refuse is not put to the person. @throws {InvalidEditProblems} */
593
+ async function validateMutation(reader, exec) {
594
+ const args = exec.arguments;
595
+ if (exec.name !== "create_world_element" && exec.name !== "replace_world_element" && exec.name !== "write_world_trigger") return;
596
+ const { record } = await reader.read(exec);
597
+ const world = {
598
+ id: record.summary.id,
599
+ directory: record.directory
600
+ };
601
+ const key = String(args["key"]);
602
+ if (exec.name === "write_world_trigger") {
603
+ await writeTriggerDocument(record.directory, await loadWorldParts(record.directory), key, args["document"], { dryRun: true });
604
+ return;
605
+ }
606
+ await (exec.name === "create_world_element" ? createAuthoredEntity : replaceAuthoredEntity)(world, args["kind"], key, args["document"], {
607
+ refuseUnread: true,
608
+ dryRun: true
609
+ });
610
+ }
592
611
  /** The most problems a write reports back; `check_world` lists the rest. */
593
612
  const REPORTED_PROBLEMS = 8;
594
613
  /**
@@ -821,6 +840,16 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
821
840
  reason: `an import may change only the prose prompts (${PROSE_PROMPTS.join(", ")}); "${String(args["id"])}" holds rules of the game and is left to the person`
822
841
  };
823
842
  if (importing || auto) return await next();
843
+ try {
844
+ if (exec.name === "edit_world_relationship") parseRelationEdit(args["change"]);
845
+ else await options.validate?.(exec);
846
+ } catch (error) {
847
+ if (error instanceof InvalidEditProblems) return {
848
+ kind: "deny",
849
+ reason: error.message
850
+ };
851
+ throw error;
852
+ }
824
853
  if (pack) {
825
854
  const target = `file “${String(args["path"])}” of interface pack “${String(args["pack"])}”`;
826
855
  const remove = exec.name.startsWith("delete");
@@ -1282,6 +1311,7 @@ function apply(ctx) {
1282
1311
  };
1283
1312
  ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing, {
1284
1313
  auto: () => ctx.roleplayImport.settings.approval === "auto",
1314
+ validate: (exec) => validateMutation(reader, exec),
1285
1315
  current,
1286
1316
  info
1287
1317
  }));
@@ -2,6 +2,19 @@ import { randomUUID } from "node:crypto";
2
2
  import { SessionId } from "@deepseek-ai/dsh-session";
3
3
  import { ReasoningEffortId, createUserMessage, lastAssistantStreamChunk } from "@deepseek-ai/dsh-llm";
4
4
  import { ToolArgsError, validateJsonSchemaValue } from "@deepseek-ai/dsh-tools";
5
+ // src/shared/chat.ts
6
+ const CHAT_PREFIX = "session-";
7
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
8
+ /** The DSH chat of a roleplay session is named after the session's id. */
9
+ function chatSessionId(sessionId) {
10
+ return `${CHAT_PREFIX}${sessionId}`;
11
+ }
12
+ /** The roleplay session a DSH chat id could belong to; ordinary DSH chats have ids of the same shape. */
13
+ function roleplaySessionOf(chat) {
14
+ if (!chat.startsWith(CHAT_PREFIX)) return void 0;
15
+ const id = chat.slice(8);
16
+ return UUID_V4.test(id) ? id : void 0;
17
+ }
5
18
  // src/host/agents/budget.ts
6
19
  /** 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. */
7
20
  function tokensOf$1(characters, language) {
@@ -274,6 +287,84 @@ function parseSampling(value, where, problems) {
274
287
  function sharedSamplingOf(settings) {
275
288
  return Object.fromEntries(SHARED_SAMPLING.flatMap((key) => settings[key] === SAMPLING_RANGES[key].neutral ? [] : [[key, settings[key]]]));
276
289
  }
290
+ // src/host/observability/trace.ts
291
+ function tracerOf(ctx) {
292
+ const found = ctx.get("aiTrace");
293
+ return typeof found?.start === "function" && typeof found.link === "function" ? found : void 0;
294
+ }
295
+ const TAGS = ["roleplay"];
296
+ /** Where a chat's work belongs in the trace: the story is the Langfuse session, so everything a story does is found under it. */
297
+ const sessionOfChat = (chat) => roleplaySessionOf(chat) ?? chat;
298
+ /** A span for work with no turn around it (an autonomy tick, an off-stage round, a background job), filed under the story. */
299
+ function startHelperSpan(tracer, chat, start) {
300
+ const parent = tracer.linked(chat);
301
+ return tracer.start({
302
+ ...start,
303
+ parent,
304
+ ...parent === void 0 ? { trace: {
305
+ name: start.name,
306
+ sessionId: sessionOfChat(chat),
307
+ tags: TAGS
308
+ } } : {}
309
+ });
310
+ }
311
+ /**
312
+ * One trace per turn: its span is open from the game master's first step to the turn's end, linked to the chat so that the game master's
313
+ * requests and every helper the turn starts nest under it.
314
+ */
315
+ var TurnTraces = class {
316
+ tracer;
317
+ open = /* @__PURE__ */ new Map();
318
+ constructor(tracer) {
319
+ this.tracer = tracer;
320
+ }
321
+ begin(chat, turn, input) {
322
+ const tracer = this.tracer();
323
+ if (tracer === void 0) return;
324
+ this.end(chat, { metadata: { ended: "replaced by a later turn" } });
325
+ const span = tracer.start({
326
+ name: `turn ${turn}`,
327
+ kind: "agent",
328
+ input,
329
+ metadata: { turn },
330
+ trace: {
331
+ name: `turn ${turn}`,
332
+ sessionId: sessionOfChat(chat),
333
+ tags: TAGS
334
+ }
335
+ });
336
+ this.open.set(chat, {
337
+ span,
338
+ unlink: tracer.link(chat, span.ref)
339
+ });
340
+ }
341
+ of(chat) {
342
+ return this.open.get(chat)?.span.ref;
343
+ }
344
+ /** What the player was shown, which becomes the output of the turn's trace. */
345
+ output(chat, text) {
346
+ const held = this.open.get(chat);
347
+ if (held !== void 0) held.output = text;
348
+ }
349
+ /** A span for a piece of the turn (a round of characters), filed under it; absent when nothing is traced. */
350
+ child(chat, start) {
351
+ const parent = this.open.get(chat)?.span.ref;
352
+ return parent === void 0 ? void 0 : this.tracer()?.start({
353
+ ...start,
354
+ parent
355
+ });
356
+ }
357
+ end(chat, result) {
358
+ const held = this.open.get(chat);
359
+ if (held === void 0) return;
360
+ this.open.delete(chat);
361
+ held.unlink();
362
+ held.span.end({
363
+ ...held.output === void 0 ? {} : { output: held.output },
364
+ ...result
365
+ });
366
+ }
367
+ };
277
368
  // src/host/agents/child.ts
278
369
  /** The tool every child ends with: its arguments are the child's result. */
279
370
  const SUBMIT_TOOL = "submit_result";
@@ -719,6 +810,20 @@ async function execute(task, stats) {
719
810
  }
720
811
  };
721
812
  helpers.set(childId, entry);
813
+ const tracer = tracerOf(parent.ctx);
814
+ const chat = String(parent.session.id);
815
+ const span = tracer === void 0 ? void 0 : startHelperSpan(tracer, chat, {
816
+ name: task.persona.split("\n", 1)[0].slice(0, 80),
817
+ kind: "agent",
818
+ input: task.prompt,
819
+ metadata: {
820
+ turn: task.turn ?? currentTurn(parent),
821
+ session: sessionOfChat(chat),
822
+ tools: (task.tools ?? []).map((tool) => tool.name),
823
+ external: task.external ?? []
824
+ }
825
+ });
826
+ const unlink = span === void 0 ? void 0 : tracer?.link(String(childId), span.ref);
722
827
  if (task.structured === true) {
723
828
  const { toolChoice: _unused, ...rest } = task.sampling ?? {};
724
829
  samplings.set(childId, {
@@ -776,9 +881,23 @@ async function execute(task, stats) {
776
881
  setTimeout(resolve, STOP_GRACE_MS);
777
882
  })]) : activation.dispose());
778
883
  }
884
+ } catch (error) {
885
+ span?.update({
886
+ level: "ERROR",
887
+ statusMessage: error instanceof Error ? error.message : String(error)
888
+ });
889
+ throw error;
779
890
  } finally {
780
891
  helpers.delete(childId);
781
892
  samplings.delete(childId);
893
+ unlink?.();
894
+ span?.end({
895
+ ...submitted === void 0 ? {} : { output: submitted.value },
896
+ metadata: {
897
+ calls: stats.calls,
898
+ tokens: stats.tokens ?? NO_TOKENS
899
+ }
900
+ });
782
901
  }
783
902
  if (signal.aborted) throw new Error("cancelled");
784
903
  if (rambled && submitted === void 0) throw new Error(`the agent wrote text up to the limit of ${task.maxTokens ?? task.sampling?.maxTokens ?? "its model"} tokens and never called ${SUBMIT_TOOL}, and was stopped`);
@@ -791,6 +910,6 @@ async function execute(task, stats) {
791
910
  }
792
911
  return submitted.value;
793
912
  }
794
- export { cutOff as C, tokensOf$1 as E, currentTurn as S, estimateAnswer as T, estimateTokens as _, childTrace as a, addTokens as b, namedModel as c, parseSampling as d, sharedSamplingOf as f, blockText as g, requestsOf as h, childSamplingOf as i, runChild as l, RECOVERY_SHRINK as m, childModel as n, helpers as o, RECOVERY_FLOOR as p, childSampling as r, isUnfinishedCall as s, ChildTimeoutError as t, SAMPLING_RANGES as u, tokensOf as v, finishOf as w, totalTokens as x, NO_TOKENS as y };
913
+ export { chatSessionId as A, addTokens as C, finishOf as D, cutOff as E, estimateAnswer as O, NO_TOKENS as S, currentTurn as T, RECOVERY_SHRINK as _, childTrace as a, estimateTokens as b, namedModel as c, sessionOfChat as d, tracerOf as f, RECOVERY_FLOOR as g, sharedSamplingOf as h, childSamplingOf as i, roleplaySessionOf as j, tokensOf$1 as k, runChild as l, parseSampling as m, childModel as n, helpers as o, SAMPLING_RANGES as p, childSampling as r, isUnfinishedCall as s, ChildTimeoutError as t, TurnTraces as u, requestsOf as v, totalTokens as w, tokensOf as x, blockText as y };
795
914
 
796
- //# sourceMappingURL=child-C9nPIy9j.js.map
915
+ //# sourceMappingURL=child-D3QUNb3m.js.map